re: AoC Day 12: Subterranean Sustainability VIEW POST

VIEW FULL DISCUSSION
 

Python.

Part 1

from more_itertools import windowed
from more_itertools import with_iter
from itertools import takewhile

initial = "##...#......##......#.####.##.#..#..####.#.######.##..#.####...##....#.#.####.####.#..#.######.##..."

rules = dict(tuple(l.strip().split(" => ")) for l in with_iter(open("input.txt")))

def dot_count(s):
    return sum(1 for _ in takewhile(lambda c: c == '.', s))

current = "....." + initial + "....."
first = -5
for i in range(20):
    new_pop = "".join(rules.get("".join(w), ".") for w in windowed(current, 5)) 
    c = dot_count(new_pop)
    first = first + c - 3
    current = "....." + new_pop.rstrip(".").lstrip(".") + "....."

print(sum(i for c, i in zip(current, range(first, len(current)+first)) if c == '#'))

Part 2

encountered = dict()
current = "....." + initial + "....."
first = -5
for i in range(100): # cycle detected at i=97
    new_pop = "".join(rules.get("".join(w), ".") for w in windowed(current, 5)) 
    c = dot_count(new_pop)
    first = first + c - 3
    current = "....." + new_pop.rstrip(".").lstrip(".") + "....."

    if current in encountered:
        continue
    else:
        encountered[current] = i

first += (50000000000-100) * (c-3)
print(sum(i for c, i in zip(current, range(first, len(current)+first)) if c == '#'))
code of conduct - report abuse