aoc2022/10/cpu.py
2022-12-10 20:51:47 +01:00

43 lines
1.3 KiB
Python

import fileinput
class CPU:
def __init__(self):
self.reg_x = 1
self.cycle = 0
def draw(self):
pos = self.cycle - 1
if pos % 40 == 0 and pos != 0:
print('')
print("#" if abs((pos % 40) - self.reg_x) <= 1 else ".", end='')
if self.cycle == 240:
print("")
def exec(self, instructions, breaks=[]):
for instruction in instructions:
# print(f"Start cycle {self.cycle:3d}: begin executing {instruction}")
if instruction == "noop":
self.cycle += 1
if self.cycle in breaks:
yield self.cycle*self.reg_x
self.draw()
elif instruction.startswith("addx"):
self.cycle += 1
if self.cycle in breaks:
yield self.cycle*self.reg_x
self.draw()
self.cycle += 1
if self.cycle in breaks:
yield self.cycle*self.reg_x
self.draw()
self.reg_x += int(instruction.split(' ')[1])
else:
print("Unknown instruction")
if __name__ == "__main__":
cpu = CPU()
print(f"Solution A: {sum(cpu.exec(filter(lambda x: x != '', map(lambda x: x.strip(), fileinput.input())), [20, 60, 100, 140, 180, 220]))}")