From f40fdcc8c3b0c55d46a3ae070b6576e89786dddc Mon Sep 17 00:00:00 2001 From: Andrew Ekstedt Date: Fri, 9 Dec 2022 21:53:36 -0800 Subject: [PATCH] day 10 python rewrite pass around an iterator of X states instead of using a callback and global variables. --- day10/sol.py | 64 ++++++++++++++++++++++++++++------------------------ 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/day10/sol.py b/day10/sol.py index 21636a8..1b4e0d1 100644 --- a/day10/sol.py +++ b/day10/sol.py @@ -1,35 +1,39 @@ +import itertools +import time -cycle = 0 -X = 1 -T = 0 -def step(): - global T - global cycle - cycle += 1 - if cycle in (20, 60, 100, 140, 180, 220): - ss = cycle * X - T += ss +def run(input): + x = 1 + for line in input: + ins = line.strip() + if ins == "noop": + yield x + else: # addx + yield x + yield x + x += int(line.split()[1]) - px = (cycle-1) % 40 - if abs(X - px) <= 1: - # sprite is visible - img.append('#') - else: - img.append(' ') +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) -img = [] +xs = list(run(open("input"))) +print(signal(xs)) -for line in open("input"): - ins = line.strip() - if ins == "noop": - step() - else: - step() - step() - X += int(line.split()[1]) - -print (T) - -for i in range(0, len(img), 40): - print(''.join(img[i:i+40])) +img = render(xs) +for line in img: + print(line) + time.sleep(.1) # :)