advent-of-code/2022/python/day10.py

76 lines
1.6 KiB
Python
Raw Normal View History

2022-12-10 06:01:44 +00:00
import shared
from anim import Animate
import matrix
cycles = {
2022-12-12 07:41:14 +00:00
"noop": 1,
"addx": 2,
}
2022-12-10 06:01:44 +00:00
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
2022-12-12 07:41:14 +00:00
if cycle_count == 20 or ((cycle_count - 20) % 40 == 0):
signal_strength.append(cycle_count * X)
2022-12-10 06:01:44 +00:00
if opcode == "addx":
X += val
print(sum(signal_strength))
def part2(x):
def cycle_to_xy(cycle):
x = cycle % 40
y = cycle // 40
2022-12-12 07:41:14 +00:00
return x, y
2022-12-10 06:01:44 +00:00
2022-12-12 07:41:14 +00:00
screen = matrix.matrix_of_size(40, 6)
2022-12-10 06:01:44 +00:00
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]):
2022-12-12 07:41:14 +00:00
_x, y = cycle_to_xy(cycle_count)
criteria = (X - 1, X, X + 1)
2022-12-10 06:01:44 +00:00
cycle_count += 1
if _x in criteria:
screen[y][_x] = 1
if opcode == "addx":
X += val
2022-12-12 07:41:14 +00:00
matrix.ppmx(screen, pad=False, space=False)
2022-12-10 06:01:44 +00:00
anim = Animate(screen, day="10")
anim.add_frame(screen)
print("wrote gif-10/day10.gif")
2022-12-12 07:41:14 +00:00
2022-12-10 06:01:44 +00:00
def main():
rows = [row for row in shared.load(10)]
part1(rows)
2022-12-12 07:41:14 +00:00
print("%" * 40)
2022-12-10 06:01:44 +00:00
part2(rows)
if __name__ == "__main__":
main()