summaryrefslogtreecommitdiffstats
path: root/20.py
blob: 707c2b0260a14dd07db129115a4444d9210b6e42 (plain)
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
from utils import open_day

bg = False
img = dict()
with open_day(20) as f:
    first, rest = f.read().rstrip().split('\n\n')
    alg = [c == '#' for c in first]
    assert(len(alg) == 512)
    for y, line in enumerate(rest.split('\n')):
        for x, c in enumerate(line):
            img[(x, y)] = c == '#'

def bits_at(img, x, y):
    bits = []
    for dy in range(-1, 2):
        for dx in range(-1, 2):
            bits.append(img.get((x + dx, y + dy), bg))
    return sum(b * 2 ** i for i, b in enumerate(reversed(bits)))

def iter():
    global bg, img
    new = dict()
    minx, maxx = float('inf'), float('-inf')
    miny, maxy = float('inf'), float('-inf')
    for p, v in img.items():
        if not v: continue
        x, y = p
        minx, maxx = min(minx, x), max(maxx, x)
        miny, maxy = min(miny, y), max(maxy, y)
    for y in range(miny - 1, maxy + 2):
        for x in range(minx - 1, maxx + 2):
            new[(x, y)] = alg[bits_at(img, x, y)]
    img = new
    bg = not bg

for _ in range(2): iter()
print(sum(img.values()))
for _ in range(48): iter()
print(sum(img.values()))