advent-of-code/2022/python/day10.py
2022-12-10 01:01:44 -05:00

77 lines
1.7 KiB
Python

import shared
from anim import Animate
import matrix
cycles = {
"noop": 1,
"addx": 2,
}
def part1(x):
X = 1
cycle_count = 0
signal_strength = []
for step, instruction in enumerate(x):
val = None
if instruction.startswith("addx"):
opcode, val = instruction.split(" ")
val = int(val)
else:
opcode = instruction
for x in range(cycles[opcode]):
cycle_count += 1
if cycle_count == 20 or ((cycle_count -20) % 40 == 0):
signal_strength.append(cycle_count*X)
if opcode == "addx":
X += val
print(sum(signal_strength))
def part2(x):
def cycle_to_xy(cycle):
x = cycle % 40
y = cycle // 40
return x,y
screen = matrix.matrix_of_size(40,6)
X = 1
cycle_count = 0
for step, instruction in enumerate(x):
val = None
if instruction.startswith("addx"):
opcode, val = instruction.split(" ")
val = int(val)
else:
opcode = instruction
for x in range(cycles[opcode]):
_x,y = cycle_to_xy(cycle_count)
criteria = (X-1, X, X+1)
cycle_count += 1
if _x in criteria:
#print("draw", _x,y)
screen[y][_x] = 1
if opcode == "addx":
X += val
matrix.ppmx(screen,pad=False, space=False)
anim = Animate(screen, day="10")
anim.add_frame(screen)
print("wrote gif-10/day10.gif")
def main():
rows = [row for row in shared.load(10)]
part1(rows)
print("%"*40)
part2(rows)
if __name__ == "__main__":
main()