day 20
trench map
approach
the image is a dictionary of lit pixels with a default value for everything else. each enhancement step reads the 3×3 neighbourhood of every pixel (plus a margin around the image) as a 9-bit number and looks it up in the enhancement algorithm.
the catch, which the code calls out in a comment: if the algorithm maps 000000000 to #, the infinite dark background turns lit after one step, and back off after the next if the last entry is .. so the dictionary's default flips each step between algo[0] and algo[-1]. part 1 runs 2 steps and part 2 runs 50, then counts lit pixels.
the trick
keep track of what "infinity" looks like: the background can blink.
python
def steps(lit, algo, n):
infinity = "."
for i in range(n):
infinity = algo[0] if infinity == "." else algo[-1]
lit = enhance(lit, algo, infinity)
return lit