-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
119 lines (110 loc) · 2.07 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"fmt"
"github.com/jdrst/adventofgo/util"
)
func main() {
fmt.Printf("First part: %v\n", partOne(util.ReadFile("input.txt")))
fmt.Printf("Second part: %v\n", partTwo(util.ReadFile("input.txt")))
}
type point struct {
x, y int
}
type octopus struct {
energy int
flashed bool
}
func partOne(file util.File) int {
lines := file.AsLines()
octopuses := [10][10]*octopus{}
for i, l := range lines {
for j, o := range l.SubSplitWith("").AsInts() {
octopuses[i][j] = &octopus{energy: o, flashed: false}
}
}
flashes := 0
for i := 0; i < 100; i++ {
flashes += doStep(octopuses)
}
return flashes
}
func partTwo(file util.File) int {
lines := file.AsLines()
octopuses := [10][10]*octopus{}
for i, l := range lines {
for j, o := range l.SubSplitWith("").AsInts() {
octopuses[i][j] = &octopus{energy: o, flashed: false}
}
}
i := 0
for {
for _, l := range octopuses {
for _, o := range l {
if !o.flashed {
goto cont
}
}
}
return i
cont:
doStep(octopuses)
i++
}
}
func doStep(octopuses [10][10]*octopus) int {
flashes := 0
for _, l := range octopuses {
for _, o := range l {
if o.flashed {
o.energy = 0
}
o.energy++
o.flashed = false
}
}
hasFlashed := true
for hasFlashed {
hasFlashed = false
for i, l := range octopuses {
for j, o := range l {
if o.energy > 9 && !o.flashed {
flashes++
hasFlashed = true
o.flashed = true
for _, p := range adjacent(i, j) {
octopuses[p.x][p.y].energy = octopuses[p.x][p.y].energy + 1
}
}
}
}
}
return flashes
}
func adjacent(x, y int) []point {
res := make([]point, 0)
if x > 0 {
res = append(res, point{x - 1, y})
if y > 0 {
res = append(res, point{x - 1, y - 1})
}
}
if x < 9 {
res = append(res, point{x + 1, y})
if y < 9 {
res = append(res, point{x + 1, y + 1})
}
}
if y < 9 {
res = append(res, point{x, y + 1})
if x > 0 {
res = append(res, point{x - 1, y + 1})
}
}
if y > 0 {
res = append(res, point{x, y - 1})
if x < 9 {
res = append(res, point{x + 1, y - 1})
}
}
return res
}