day 10 python rewrite

pass around an iterator of X states instead of using a callback and
global variables.
main
magical 2022-12-09 21:53:36 -08:00
parent 4ea896feeb
commit f40fdcc8c3
1 changed files with 34 additions and 30 deletions

View File

@ -1,35 +1,39 @@
import itertools
import time
cycle = 0 def run(input):
X = 1 x = 1
T = 0 for line in input:
def step(): ins = line.strip()
global T if ins == "noop":
global cycle yield x
cycle += 1 else: # addx <num>
if cycle in (20, 60, 100, 140, 180, 220): yield x
ss = cycle * X yield x
T += ss x += int(line.split()[1])
px = (cycle-1) % 40 def signal(xs):
if abs(X - px) <= 1: t = 0
# sprite is visible for cycle, x in enumerate(xs, start=1):
img.append('#') if cycle % 40 == 20:
else: signal_strength = cycle * x
img.append(' ') 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)
img = [] xs = list(run(open("input")))
print(signal(xs))
for line in open("input"): img = render(xs)
ins = line.strip() for line in img:
if ins == "noop": print(line)
step() time.sleep(.1) # :)
else:
step()
step()
X += int(line.split()[1])
print (T)
for i in range(0, len(img), 40):
print(''.join(img[i:i+40]))