advent/2018/12.py

63 lines
1.5 KiB
Python
Raw Normal View History

2018-12-13 06:06:14 +00:00
import re
2018-12-13 00:33:01 +00:00
def to_int(bitlist):
out = 0
for bit in bitlist:
out = out * 2 + bit
return out
2018-12-13 06:06:14 +00:00
def grow(init, num_gens, progress=False):
first, last = min(init), max(init)
current_gen = set(init)
2018-12-13 00:33:01 +00:00
for g in range(num_gens):
2018-12-13 06:06:14 +00:00
next_gen = set()
for i in range(first - 2, last + 3):
key = to_int(1 if b in current_gen else 0 for b in range(i - 2, i + 3))
2018-12-13 00:33:01 +00:00
if key in positives:
2018-12-13 06:06:14 +00:00
next_gen.add(i)
if i < first:
first = i
if i > last:
last = i
2018-12-13 00:33:01 +00:00
current_gen = next_gen
2018-12-13 06:06:14 +00:00
if progress:
print('Generations:', g + 1, end='\r')
if progress: print('Generations:', g + 1)
2018-12-13 00:33:01 +00:00
return current_gen
2018-12-13 06:06:14 +00:00
def test(n):
pots = grow(initial, n)
first, last = min(pots), max(pots)
chars = []
for i in range(first - 1, last + 2):
chars.append('#' if i in pots else '.')
print(''.join(chars))
2018-12-13 00:33:01 +00:00
with open('data/12.txt') as f:
2018-12-13 06:06:14 +00:00
initial = re.search('[#.]+', next(f)).group(0)
initial = {i for i, p in enumerate(initial) if p == '#'}
2018-12-13 00:33:01 +00:00
next(f)
2018-12-13 06:06:14 +00:00
2018-12-13 00:33:01 +00:00
positives, negatives = set(), set()
for line in f:
state, result = line.strip().split(' => ')
s = to_int(int(c == '#') for c in state)
if result == '#':
positives.add(s)
else:
negatives.add(s)
2018-12-13 06:06:14 +00:00
pots = grow(initial, 20)
print(f'Part 1: {sum(pots)}\n')
pots = grow(initial, 5 * 10 ** 10, True)
print(f'Part 2: {pots}\n')
2018-12-13 00:33:01 +00:00