]> git.friedersdorff.com Git - max/advent_of_code_2021.git/blob - 11_3.py
Try day 14
[max/advent_of_code_2021.git] / 11_3.py
1 """ Simulate octopus flashing """
2 import time
3 import random
4
5 rows = 3
6 cols = 3
7
8 def increment(octopodes, position):
9     for x in range(position[0] - 1, position[0] + 2):
10         if x < 0 or x > cols - 1:
11             continue
12
13         for y in range(position[1] - 1, position[1] + 2):
14             if y < 0 or y > rows - 1:
15
16                 continue
17
18             octopodes[y][x] += 1
19
20
21 def add_one(octopodes):
22     for y in range(rows):
23         for x in range(cols):
24             octopodes[y][x] += 1
25
26
27 def flash(octopodes):
28     flashed = []
29
30     flashed_this_iter = True
31     while flashed_this_iter:
32         flashed_this_iter = False
33         for y in range(rows):
34             for x in range(cols):
35                 if octopodes[y][x] > 9 and (x, y) not in flashed:
36                     flashed_this_iter = True
37                     flashed.append((x, y))
38                     increment(octopodes, (x, y))
39
40     for x, y in flashed:
41         octopodes[y][x] = 0
42
43     #for y in range(20):
44     #    display_row = []
45     #    for x in range(40):
46     #        if (x, y) in flashed:
47     #            display_row.append("X")
48     #        else:
49     #            display_row.append(".")
50     #    print("".join(display_row))
51
52
53     return len(flashed)
54
55
56 octopodes = []
57 for i in range(rows):
58     octopodes.append([random.randint(0, 9) for _ in range(cols)])
59
60 for gen in range(1, 100000000):
61     add_one(octopodes)
62     n_flashed = flash(octopodes)
63     if gen % 100 == 0:
64         print("###", gen, "###", n_flashed)
65
66     if n_flashed == (rows * cols):
67         break
68
69 print(gen)