day 10 python rewrite
pass around an iterator of X states instead of using a callback and global variables.main
parent
4ea896feeb
commit
f40fdcc8c3
64
day10/sol.py
64
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 <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) # :)
|
||||
|
|
Loading…
Reference in New Issue