Andrew Ekstedt 831d8e4f23 day 10 python rewrite
pass around an iterator of X states instead of using a callback and
global variables.
2022-12-09 22:01:24 -08:00

40 lines
821 B
Python

import itertools
import time
def run(input):
x = 1
for line in input:
ins = line.strip()
if ins == "noop":
yield x
else: # addx <num>
yield x
yield x
x += int(line.split()[1])
def signal(xs):
t = 0
for cycle, x in enumerate(xs, start=1):
if cycle % 40 == 20:
signal_strength = cycle * x
t += signal_strength
return t
def render(xs):
xs = iter(xs)
while True:
img = []
for pos, x in enumerate(itertools.islice(xs, 40)):
visible = x-1 <= pos <= x+1
img.append(' #'[visible])
if not img: return
yield ''.join(img)
xs = list(run(open("input")))
print(signal(xs))
img = render(xs)
for line in img:
print(line)
time.sleep(.1)