generated from devries/aoc_template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.go
84 lines (68 loc) · 1.54 KB
/
solution.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
package day03p1
import (
"io"
"aoc/utils"
)
func Solve(r io.Reader) any {
lines := utils.ReadLines(r)
symbols := make(map[utils.Point]rune)
numbers := []Number{}
for j, ln := range lines {
innumber := false
for i, r := range ln {
switch {
case r == '.':
// do nothing
innumber = false
case r >= '0' && r <= '9':
// number
switch innumber {
case false:
innumber = true
var newNumber Number
newNumber.Start = utils.Point{X: i, Y: j}
newNumber.End = newNumber.Start
newNumber.Value = int64(r - '0')
numbers = append(numbers, newNumber)
case true:
idx := len(numbers) - 1
numbers[idx].End = utils.Point{X: i, Y: j}
numbers[idx].Value = numbers[idx].Value*10 + int64(r-'0')
}
default:
// symbol
symbols[utils.Point{X: i, Y: j}] = r
innumber = false
}
}
}
var sum int64
for _, n := range numbers {
surroundingPoints := pointsAround(n.Start, n.End)
for _, p := range surroundingPoints {
if symbols[p] != 0 {
sum += n.Value
break
}
}
}
return sum
}
type Number struct {
Value int64
Start utils.Point
End utils.Point
}
func pointsAround(start utils.Point, end utils.Point) []utils.Point {
yupper := start.Y - 1
ylower := start.Y + 1
yline := start.Y
xmin := start.X - 1
xmax := end.X + 1
result := []utils.Point{{X: xmin, Y: yline}, {X: xmax, Y: yline}}
for i := xmin; i <= xmax; i++ {
result = append(result, utils.Point{X: i, Y: yupper})
result = append(result, utils.Point{X: i, Y: ylower})
}
return result
}