-
Notifications
You must be signed in to change notification settings - Fork 0
/
day03.go
99 lines (81 loc) · 1.84 KB
/
day03.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
92
93
94
95
96
97
98
99
package main
import (
_ "embed"
"fmt"
"strings"
)
//go:embed input.txt
var input string
func getNumber(line *string, index int) int {
var start int
for i := index - 1; i >= 0; i-- {
if (*line)[i] < '0' || (*line)[i] > '9' {
start = i + 1
break
}
}
var number int
newLine := []byte(*line)
for i := start; i < len(*line) && (*line)[i] >= '0' && (*line)[i] <= '9'; i++ {
number = number*10 + int((*line)[i]-'0')
newLine[i] = '.'
}
*line = string(newLine)
return number
}
func part1(input string) int {
lines := strings.Split(input, "\n")
var adjacent = [][2]int{{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}}
var sum int
for y := 0; y < len(lines); y++ {
for x := 0; x < len(lines[y]); x++ {
c := lines[y][x]
if (c != '.' && c < '0') || c > '9' {
for i := 0; i < len(adjacent); i++ {
nX := x + adjacent[i][0]
nY := y + adjacent[i][1]
c := lines[nY][nX]
if c >= '0' && c <= '9' {
sum += getNumber(&lines[nY], nX)
}
}
}
}
}
return sum
}
func part2(input string) int {
lines := strings.Split(input, "\n")
var adjacent = [][2]int{{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}}
var sum int
for y := 0; y < len(lines); y++ {
for x := 0; x < len(lines[y]); x++ {
c := lines[y][x]
if (c != '.' && c < '0') || c > '9' {
gearRatio := 1
var amount int
for i := 0; i < len(adjacent); i++ {
if amount > 2 {
break
}
nX := x + adjacent[i][0]
nY := y + adjacent[i][1]
c := lines[nY][nX]
if c >= '0' && c <= '9' {
amount++
gearRatio *= getNumber(&lines[nY], nX)
}
}
if amount == 2 {
sum += gearRatio
}
}
}
}
return sum
}
func main() {
fmt.Println("--- 2023 day 03 answer ---")
fmt.Println("part 1:\t", part1(input))
fmt.Println("part 2:\t", part2(input))
}