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
|
import sys
infile = sys.argv[1] if len(sys.argv) > 1 else "day20data.txt"
data = open(infile).read().strip()
rule, start = data.split("\n\n")
rule = rule.strip()
assert len(rule) == 512
G = set()
for r, line in enumerate(start.strip().split("\n")):
for c, x in enumerate(line.strip()):
if x == "#":
G.add((r, c))
def step(G, on):
G2 = set()
rlo = min([r for r, c in G])
rhi = max([r for r, c in G])
clo = min([c for r, c in G])
chi = max([c for r, c in G])
for r in range(rlo - 5, rhi + 10):
for c in range(clo - 5, chi + 10):
rc_str = 0
bit = 8
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
if ((r + dr, c + dc) in G) == on:
rc_str += 2**bit
bit -= 1
assert 0 <= rc_str < 512
if (rule[rc_str] == "#") != on:
G2.add((r, c))
return G2
def show(G):
rlo = min([r for r, c in G])
rhi = max([r for r, c in G])
clo = min([c for r, c in G])
chi = max([c for r, c in G])
for r in range(rlo - 5, rhi + 5):
row = ""
for c in range(clo - 5, chi + 5):
if (r, c) in G:
row += "#"
else:
row += " "
print(row)
for t in range(50):
if t == 2:
print(len(G))
G = step(G, t % 2 == 0)
print(len(G))
|