Skip to content

Commit 64a369b

Browse files
committed
Add solution to 2024-12-17
1 parent 2db1026 commit 64a369b

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

2024/day17/solutions.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from itertools import count
2+
3+
program = [2, 4, 1, 1, 7, 5, 1, 5, 4, 5, 0, 3, 5, 5, 3, 0]
4+
5+
6+
def run(A):
7+
ptr = 0
8+
B = 0
9+
C = 0
10+
result = []
11+
while True:
12+
try:
13+
ins = program[ptr]
14+
op = program[ptr + 1]
15+
except:
16+
return result
17+
if op <= 3:
18+
combo = op
19+
elif op == 4:
20+
combo = A
21+
elif op == 5:
22+
combo = B
23+
elif op == 6:
24+
combo = C
25+
26+
match ins:
27+
case 0:
28+
A //= 2**combo
29+
case 1:
30+
B ^= op
31+
case 2:
32+
B = combo % 8
33+
case 3:
34+
if A != 0:
35+
ptr = op - 2
36+
case 4:
37+
B ^= C
38+
case 5:
39+
result.append(combo % 8)
40+
case 6:
41+
B = A // (2**combo)
42+
case 7:
43+
C = A // (2**combo)
44+
ptr += 2
45+
46+
47+
# Part 1
48+
print(run(30344604))
49+
50+
51+
# Part 2
52+
mid = int(next(A for i in count() if len(run(A := 10**i)) == len(program))) * 10
53+
width = mid
54+
spacing = width // 1000
55+
for matching_digits in range(1, len(program) + 1):
56+
for A in range(mid - width, mid + width, spacing):
57+
res = run(A)
58+
if (
59+
len(res) == len(program)
60+
and res[-matching_digits:] == program[-matching_digits:]
61+
):
62+
break
63+
else:
64+
assert False
65+
mid = A
66+
spacing //= 10
67+
width //= 10
68+
if spacing <= 10:
69+
spacing = 1
70+
if width <= 10000:
71+
width = 100000
72+
73+
print(A)

0 commit comments

Comments
 (0)