-
Notifications
You must be signed in to change notification settings - Fork 0
/
24.py
92 lines (74 loc) · 2.45 KB
/
24.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from lib import *
input = read_input(2019, 24)
grid = sum((1 << i * 5 + j) * (c == "#") for i, line in enumerate(input.splitlines()) for j, c in enumerate(line))
def get_adjacent(i, j):
return sum(
grid & (1 << i * 5 + j) > 0
for i, j in [(i, j - 1), (i, j + 1), (i - 1, j), (i + 1, j)]
if i in range(5) and j in range(5)
)
def simulate():
out = 0
for i in range(5):
for j in range(5):
if (grid & (1 << i * 5 + j) > 0 and get_adjacent(i, j) == 1) or (
grid & (1 << i * 5 + j) == 0 and get_adjacent(i, j) in (1, 2)
):
out |= 1 << i * 5 + j
return out
history = set()
while True:
if grid in history:
break
history.add(grid)
grid = simulate()
print(grid)
grid = {0: sum((1 << i * 5 + j) * (c == "#") for i, line in enumerate(input.splitlines()) for j, c in enumerate(line))}
def is_alive(i, j, l):
return grid.get(l, 0) & (1 << i * 5 + j) > 0
def get_adjacent(i, j, l):
if (i, j) == (2, 2):
return 0
out = 0
for x, y in [(j - 1, i), (j + 1, i), (j, i - 1), (j, i + 1)]:
outer = grid.get(l - 1, 0)
layer = grid.get(l, 0)
inner = grid.get(l + 1, 0)
if (x, y) == (2, 2):
for k in range(5):
if i == 1:
out += is_alive(0, k, l + 1)
elif j == 1:
out += is_alive(k, 0, l + 1)
elif i == 3:
out += is_alive(4, k, l + 1)
elif j == 3:
out += is_alive(k, 4, l + 1)
else:
if x == -1:
out += is_alive(2, 1, l - 1)
elif y == -1:
out += is_alive(1, 2, l - 1)
elif x == 5:
out += is_alive(2, 3, l - 1)
elif y == 5:
out += is_alive(3, 2, l - 1)
else:
out += is_alive(y, x, l)
return out
def simulate():
out = {}
for l in range(min(grid) - 1, max(grid) + 2):
lout = 0
for i in range(5):
for j in range(5):
if (is_alive(i, j, l) and get_adjacent(i, j, l) == 1) or (
not is_alive(i, j, l) and get_adjacent(i, j, l) in (1, 2)
):
lout |= 1 << i * 5 + j
if lout:
out[l] = lout
return out
for _ in range(200):
grid = simulate()
print(sum(bin(layer).count("1") for layer in grid.values()))