-
Notifications
You must be signed in to change notification settings - Fork 0
/
11.py
56 lines (40 loc) · 1.27 KB
/
11.py
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
from itertools import product, count
from utils import rinput, iter_lines
def parse(inp):
return {
(x, y): int(v)
for y, line in enumerate(iter_lines(inp))
for x, v in enumerate(line)
}
def neighbourhood(coords):
x, y = coords
for n in product(range(x - 1, x + 2), range(y - 1, y + 2)):
if n != coords:
yield n
def sim_step(grid):
for coords in grid:
grid[coords] += 1
flashes = [coords for coords, energy in grid.items() if energy > 9]
has_flashed = set(flashes)
while flashes:
curr = flashes.pop()
has_flashed.add(curr)
for neighbour in neighbourhood(curr):
if neighbour in grid:
grid[neighbour] += 1
if grid[neighbour] > 9 and neighbour not in has_flashed:
flashes.append(neighbour)
has_flashed.add(neighbour)
for flashed in has_flashed:
grid[flashed] = 0
return len(has_flashed)
def solve1(inp, steps=100):
grid = parse(inp)
return sum(sim_step(grid) for _ in range(steps))
def solve2(inp):
grid = parse(inp)
for step in count():
if sim_step(grid) == len(grid.values()):
return step + 1
print(solve1(rinput(11)))
print(solve2(rinput(11)))