-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3_part2.go
91 lines (79 loc) · 1.67 KB
/
day3_part2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package day3_part2
import (
"strings"
"GoAdventOfCode/util"
)
func sumOfAllOfTheGearRatios(schematic []string) int {
sum := 0
isDigit := func(ch byte) bool {
return ch >= byte('0') && ch <= byte('9')
}
isAsterisk := func(ch string) bool {
return strings.ContainsAny(ch, "*")
}
isSymbol := func(ch string) bool {
return strings.ContainsAny(ch, "#$%&+-/=@")
}
type position struct {
X int
Y int
}
parts := make(map[position]int)
symbols := make(map[string]int)
isPartNumber := func(sx int, sy int, size int) (bool, position) {
for y := sy - 1; y <= sy+1; y++ {
for x := sx - 1; x <= sx+size; x++ {
if x >= 0 && y >= 0 && x < len(schematic[0]) && y < len(schematic) {
ch := schematic[y][x]
if ch == '.' {
continue
}
if isDigit(ch) {
continue
}
if isAsterisk(string(ch)) {
return true, position{X: x, Y: y}
}
if isSymbol(string(ch)) {
return true, position{X: x, Y: y}
}
}
}
}
return false, position{X: 0, Y: 0}
}
for y := 0; y < len(schematic); y++ {
process := false
number := ""
for x := 0; x < len(schematic[y]); x++ {
ch := schematic[y][x]
symbols[string(ch)]++
if isDigit(ch) {
number += string(ch)
} else {
process = true
}
if x == len(schematic)-1 {
process = true
}
if process {
size := len(number)
if size > 0 {
isPart, pos := isPartNumber(x-size, y, size)
if isPart {
value := util.ConvertStringToInt(number)
value2, ok := parts[pos]
if ok {
sum += value * value2
} else {
parts[pos] = value
}
}
}
number = ""
process = false
}
}
}
return sum
}