-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday_11.py
72 lines (53 loc) · 1.3 KB
/
day_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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
octopuses = []
flashes = 0
with open('input_11.txt') as d:
for c in d:
octopuses.append([int(c) for c in c.strip()])
rows = len(octopuses)
cols = len(octopuses[0])
def flash(row, col):
global flashes
flashes += 1
# Set energy to -1 to indicate octopus has been
# seen this step
octopuses[row][col] = -1
# Check all adjacent octopuses
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
rr = row + dr
rc = col + dc
if 0 <= rr < rows and 0 <= rc < cols and octopuses[rr][rc] != -1:
octopuses[rr][rc] += 1
if octopuses[rr][rc] >= 10:
flash(rr, rc)
def run():
steps = 0
while True:
steps += 1
# Increment all octopuses by one
for i in range(rows):
for j in range(cols):
octopuses[i][j] += 1
# Check if any octopus has 10 energy
# This means it should flash
for i in range(rows):
for j in range(cols):
if octopuses[i][j] == 10:
flash(i, j)
done = True
# Reset octopuses and if all are at 0 energy
# it means that they've all flashed together
for i in range(rows):
for j in range(cols):
if octopuses[i][j] == -1:
octopuses[i][j] = 0
else:
done = False
# Number of flashes after 100 steps
if steps == 100:
print('Part 1:', flashes)
# All octopuses flashed together
if done:
print('Part 2:', steps)
break
run()