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