Skip to content

Commit dbe8d6b

Browse files
committed
2024: Day 17
1 parent 5680095 commit dbe8d6b

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

2024/python/day17/__init__.py

Whitespace-only changes.

2024/python/day17/__main__.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import sys
2+
3+
from utils.file import read_input
4+
5+
lines = read_input(__package__)
6+
registers = int(lines[0][12:]), int(lines[1][12:]), int(lines[2][12:])
7+
program = tuple(map(int, lines[3][9:].split(",")))
8+
end = len(program)
9+
10+
11+
def run_program(ra: int, rb: int, rc: int) -> tuple[int, ...]:
12+
def combo(value: int) -> int:
13+
match value:
14+
case 4:
15+
return ra
16+
case 5:
17+
return rb
18+
case 6:
19+
return rc
20+
case 0 | 1 | 2 | 3:
21+
return value
22+
case _:
23+
raise ValueError(f"Invalid operand {value}")
24+
25+
iptr = 0
26+
output: list[int] = []
27+
while iptr < end:
28+
opcode, operand = program[iptr], program[iptr + 1]
29+
match opcode:
30+
case 0: # adv
31+
ra = ra // 2 ** combo(operand)
32+
case 1: # bxl
33+
rb = rb ^ operand
34+
case 2: # bst
35+
rb = combo(operand) % 8
36+
case 3 if ra != 0: # jnz
37+
iptr = operand
38+
continue
39+
case 3:
40+
pass
41+
case 4: # bxc
42+
rb = rb ^ rc
43+
case 5: # out
44+
output.append(combo(operand) % 8)
45+
case 6: # bdv
46+
rb = ra // 2 ** combo(operand)
47+
case 7: # cdv
48+
rc = ra // 2 ** combo(operand)
49+
case _:
50+
return tuple()
51+
iptr += 2
52+
return tuple(output)
53+
54+
55+
print("Part 1:", ",".join(map(str, run_program(*registers))))
56+
57+
58+
def find_input(cursor: int, seed: int) -> int | None:
59+
for candidate in range(8):
60+
if run_program(seed * 8 + candidate, registers[1], registers[2]) != program[cursor:]:
61+
continue
62+
if cursor == 0:
63+
return seed * 8 + candidate
64+
if (result := find_input(cursor - 1, seed * 8 + candidate)) is not None:
65+
return result
66+
return None
67+
68+
69+
print("Part 2:", find_input(len(program) - 1, 0))

2024/python/day17/input.txt

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Register A: 30878003
2+
Register B: 0
3+
Register C: 0
4+
5+
Program: 2,4,1,2,7,5,0,3,4,7,1,7,5,5,3,0
6+
7+
while ra != 0:
8+
rb = ra % 8
9+
rb = rb ^ 2
10+
rc = ra / rb
11+
ra = ra / 3
12+
rb = rb ^ rc
13+
rb = rb ^ 7
14+
out (rb % 8)

0 commit comments

Comments
 (0)