Skip to content

Instantly share code, notes, and snippets.

@Dotrar
Created December 10, 2022 07:59
Show Gist options
  • Save Dotrar/177ec2899b782d73a0c13c438b2d675b to your computer and use it in GitHub Desktop.
Save Dotrar/177ec2899b782d73a0c13c438b2d675b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from __future__ import annotations
import aocd
test_data = """
addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop
""".splitlines()[
1:
]
assert len(test_data) == 146
test_answer_one = 13140
test_answer_two = 36
CLKS = [20, 60, 100, 140, 180, 220]
TIME = {"noop": 1, "addx": 2}
def part_one(data: list[str]) -> int:
x = 1
cycle = 0
ans = 0
for row in data:
d = row.split(" ")
op = d[0]
t = TIME[op]
for _ in range(t):
cycle += 1
if cycle in CLKS:
ans += cycle * x
# after the cycle, then add value
if op == "addx":
x += int(d[-1])
return ans
def part_two(data: list[str]) -> int:
x = 1
cycle = 0
ans = 0
rc = 0
def draw_pixel(rc):
if rc in (x, x + 1, x - 1):
print("#", end="")
else:
print(".", end="")
rc += 1
if rc == 40:
print()
rc %= 40
return rc
for row in data:
d = row.split(" ")
op = d[0]
t = TIME[op]
for _ in range(t):
cycle += 1
# draw during cycle
rc = draw_pixel(rc)
if op == "addx":
x += int(d[-1])
return ans
if __name__ == "__main__":
part_one_ans = part_one(test_data)
assert part_one_ans == test_answer_one, f"{part_one_ans=}, not {test_answer_one=}"
real_data = aocd.get_data(day=10, year=2022).splitlines()
print(real_data)
print("part 1:", part_one(real_data))
part_two_ans = part_two(test_data)
# assert part_two_ans == test_answer_two, f"{part_two_ans=}, not {test_answer_two=}"
print("part 2:", part_two(real_data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment