-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
150 lines (122 loc) · 2.47 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package main
import (
"io"
aoc "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader, steps int) int {
lines := aoc.ReaderToStrings(input)
grid := make(map[aoc.Position]int)
for row, line := range lines {
for col := 0; col < len(line); col++ {
r := rune(line[col])
grid[aoc.Position{row, col}] = aoc.RuneToInt(r)
}
}
sum := 0
for i := 0; i < steps; i++ {
sum += round(grid)
}
return sum
}
func isSynchronized(grid map[aoc.Position]int) bool {
for _, energy := range grid {
if energy != 0 {
return false
}
}
return true
}
func round(grid map[aoc.Position]int) int {
for pos := range grid {
grid[pos]++
}
flashed := make(map[aoc.Position]bool)
var q []aoc.Position
for pos, energy := range grid {
if energy > 9 {
q = append(q, pos)
}
}
for len(q) != 0 {
pos := q[0]
q = q[1:]
q = append(q, flashes(grid, pos, flashed)...)
flashed[pos] = true
}
sum := 0
for pos, energy := range grid {
if energy > 9 {
sum++
grid[pos] = 0
}
}
return sum
}
func flashes(grid map[aoc.Position]int, pos aoc.Position, flashed map[aoc.Position]bool) []aoc.Position {
if flashed[pos] {
return nil
}
if _, exists := grid[pos]; !exists {
return nil
}
var res []aoc.Position
p := pos.Move(aoc.Up, 1)
if flash(grid, p, flashed) {
res = append(res, p)
}
p = pos.Move(aoc.Down, 1)
if flash(grid, p, flashed) {
res = append(res, p)
}
p = pos.Move(aoc.Left, 1)
if flash(grid, p, flashed) {
res = append(res, p)
}
p = pos.Move(aoc.Right, 1)
if flash(grid, p, flashed) {
res = append(res, p)
}
p = pos.Move(aoc.UpLeft, 1)
if flash(grid, p, flashed) {
res = append(res, p)
}
p = pos.Move(aoc.UpRight, 1)
if flash(grid, p, flashed) {
res = append(res, p)
}
p = pos.Move(aoc.DownLeft, 1)
if flash(grid, p, flashed) {
res = append(res, p)
}
p = pos.Move(aoc.DownRight, 1)
if flash(grid, p, flashed) {
res = append(res, p)
}
return res
}
func flash(grid map[aoc.Position]int, pos aoc.Position, flashed map[aoc.Position]bool) bool {
if flashed[pos] {
return false
}
if _, exists := grid[pos]; !exists {
return false
}
grid[pos]++
return grid[pos] == 10
}
func fs2(input io.Reader) int {
lines := aoc.ReaderToStrings(input)
grid := make(map[aoc.Position]int)
for row, line := range lines {
for col := 0; col < len(line); col++ {
r := rune(line[col])
grid[aoc.Position{row, col}] = aoc.RuneToInt(r)
}
}
for i := 0; ; i++ {
round(grid)
if isSynchronized(grid) {
return i + 1
}
}
}