-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday11.py
65 lines (46 loc) · 1.44 KB
/
day11.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
57
58
59
60
61
62
63
64
from copy import deepcopy
from helper.utils import *
DAY = 11
@time_function
def prepare_data():
raw_data = parse_file_rows_to_list(DAY, test=False)
return {
(x, y): int(energy)
for x, rows in enumerate(raw_data)
for y, energy in enumerate(rows)
}
@time_function
def part_a(data):
return _sim_steps(data, 100)
@time_function
def part_b(data):
return _sim_steps(data, 1_000_000, sync=True)
def neighbours(x, y, energy_levels):
kernel = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
return filter(
energy_levels.get,
[(x + dx, y + dy) for dx, dy in kernel]
)
def _sim_steps(energy_levels, steps, sync=False):
flashes = 0
for step in range(1, steps + 1):
for position in energy_levels:
energy_levels[position] += 1
flashing = set(position for position in energy_levels if energy_levels[position] > 9)
while flashing:
position = flashing.pop()
energy_levels[position] = 0
flashes += 1
for n in neighbours(*position, energy_levels):
energy_levels[n] += 1
if energy_levels[n] > 9:
flashing.add(n)
if sync and sum(energy_levels.values()) == 0:
return step
return flashes
def main():
data = prepare_data()
part_a(deepcopy(data))
part_b(deepcopy(data))
if __name__ == '__main__':
main()