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
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 <num>
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) # :)