2024 day 17 kind-of-generic.

This commit is contained in:
Mikael CAPELLE 2024-12-17 15:20:30 +01:00
parent 11e32ddfda
commit 7c0a124a5d

View File

@ -101,17 +101,17 @@ class Solver(BaseSolver):
yield ",".join(map(str, run(registers.copy(), program))) yield ",".join(map(str, run(registers.copy(), program)))
# out_index = next(i for i in range(0, len(program), 2) if program[i] == 5) # last instruction is JNZ 0 (jump at the beginning), and it is the only jump
# out_register = "ABC"[program[out_index + 1] - 4] # in the program
# there is only one jump instruction and it goes back to the beginning of the
# program
jnz_indices = [i for i in range(0, len(program), 2) if program[i] == 3] jnz_indices = [i for i in range(0, len(program), 2) if program[i] == 3]
assert ( assert jnz_indices == [len(program) - 2] and program[-1] == 0
len(jnz_indices) == 1
and jnz_indices[0] == len(program) - 2 # previous instruction is dividing A by 8, or A = A >> 3
and program[-1] == 0 assert program[-4:-2] == [0, 3]
)
# previous instruction is a OUT B % 8, and it is the only OUT in the program
out_indices = [i for i in range(0, len(program), 2) if program[i] == 5]
assert out_indices == [len(program) - 6] and program[len(program) - 5] == 5
valid: list[int] = [0] valid: list[int] = [0]
for p in reversed(program): for p in reversed(program):
@ -119,10 +119,10 @@ class Solver(BaseSolver):
for v in valid: for v in valid:
a_high = v << 3 a_high = v << 3
for a_low in range(0, 2**3): for a_low in range(0, 2**3):
a = a_high | a_low registers["A"] = a_high | a_low
b = (((a % 8) ^ 7) ^ (a >> ((a % 8) ^ 7))) ^ 4 run(registers, program[:-6])
if b % 8 == p: if registers["B"] % 8 == p:
new_valid.append(a) new_valid.append(a_high | a_low)
valid = new_valid valid = new_valid
assert run(registers | {"A": min(valid)}, program) == program assert run(registers | {"A": min(valid)}, program) == program