Twenty-Five Days · day 17 · both parts
Day 17: Chronospatial Computer
Part 1 is an interpreter for an eight-instruction machine, about thirty lines. Part 2 turns it round: find the input that makes the program print itself. Brute force works on the example and nowhere else, and the way out is to read A in octal.
The puzzle, in my words
A small computer has three registers, A, B and C, which hold any integer, and a program made of numbers from 0 to 7, read in pairs: an opcode and its operand. The eight instructions divide A by a power of two (storing the result in A, B or C), XOR something into B, put a value mod 8 into B, jump back if A isn’t 0, or output a value mod 8. Some instructions take the operand as a plain number; others read 4, 5 and 6 as “the value in A, B, C”. Run the program and join its outputs with commas.
In the example, A starts at 729 and the program is 0,1,5,4,3,0: halve A,
output A mod 8, jump back to the start unless A is 0. It prints
4,6,3,5,6,3,5,2,1,0. The page also gives five tiny programs with what
they should print or leave in the registers, which make good tests.
Part 1: run the program
Step 1: the first version
Parse the four lines, then follow the instruction pointer with one branch per opcode. The combo operand gets a small helper. The function returns the final registers as well as the outputs, because the page’s small examples check the registers.
def execute(program: list[int], a: int, b: int, c: int):
def combo(operand):
if operand <= 3:
return operand
if operand == 4:
return a
if operand == 5:
return b
if operand == 6:
return c
raise ValueError("combo operand 7 is reserved")
out = []
ip = 0
while ip < len(program):
opcode, operand = program[ip], program[ip + 1]
if opcode == 0:
a = a // 2 ** combo(operand)
elif opcode == 1:
b = b ^ operand
elif opcode == 2:
b = combo(operand) % 8
elif opcode == 3:
if a != 0:
ip = operand
continue
elif opcode == 4:
b = b ^ c
elif opcode == 5:
out.append(combo(operand) % 8)
elif opcode == 6:
b = a // 2 ** combo(operand)
elif opcode == 7:
c = a // 2 ** combo(operand)
ip += 2
return out, (a, b, c)
def part1(text: str) -> str:
lines = text.strip().splitlines()
a = int(lines[0].split(":")[1])
b = int(lines[1].split(":")[1])
c = int(lines[2].split(":")[1])
program = [int(x) for x in lines[4].split(":")[1].split(",")]
out, _ = execute(program, a, b, c)
return ",".join(str(x) for x in out)
The puzzle says “divide and truncate”. // floors rather than truncates,
which differs for negative numbers, but the registers never go negative here:
they start non-negative, and XOR, mod 8 and division keep them that way.
Step 2: a generator, match and shifts
The same machine, tidier, and built for what part 2 needs:
import re
def parse(text: str) -> tuple[int, int, int, list[int]]:
a, b, c, *program = map(int, re.findall(r"\d+", text))
return a, b, c, program
def run(program: list[int], a: int, b: int, c: int):
ip = 0
while ip < len(program):
opcode, operand = program[ip], program[ip + 1]
combo = (0, 1, 2, 3, a, b, c, None)[operand]
match opcode:
case 0:
a >>= combo
case 1:
b ^= operand
case 2:
b = combo % 8
case 3 if a:
ip = operand
continue
case 4:
b ^= c
case 5:
yield combo % 8
case 6:
b = a >> combo
case 7:
c = a >> combo
ip += 2
return a, b, c
def part1(text: str) -> str:
a, b, c, program = parse(text)
return ",".join(map(str, run(program, a, b, c)))
What changed:
- Every number in the input, in order, is the three registers and then the
program, so one
re.findalland a starred assignment replace the line slicing. - The combo operand is an index into a tuple built fresh for each instruction, so it sees the current registers.
- For a non-negative integer,
a // 2**nanda >> nare the same thing, and the shift doesn’t build the power of two first. match(Python 3.10+) with a guard:case 3 if aonly matches a jump when A is not 0. When A is 0, no case matches, and the pointer moves on like any other instruction.runis a generator: each output is yielded as soon as it happens. The caller can stop as soon as it has seen enough, which part 2’s brute force uses. Thereturn a, b, cat the end doesn’t reachpart1; a generator’s return value ends up in theStopIterationit raises when it finishes, which is how the tests check the registers.
At this size neither version’s speed matters. On a generated program of the real inputs’ shape (16 numbers, A with 16 octal digits), both run in a few hundredths of a millisecond.
Part 2: a program that prints itself
Now ignore A’s starting value and find the lowest positive A for which the
program outputs a copy of itself. The example program is 0,3,5,4,3,0:
divide A by 8, output A mod 8, jump back unless A is 0. The answer is 117440.
Step 1: brute force
The generator lets each attempt stop at its first wrong output:
from itertools import count
def part2(text: str) -> int:
_, b, c, program = parse(text)
for a in count(1):
out = []
for value in run(program, a, b, c):
out.append(value)
if out != program[: len(out)]:
break
else:
if out == program:
return a
The else on a for loop runs only when the loop wasn’t left by break,
so it’s reached when the program halted with every output right so far; it
then checks there were enough of them.
On the example this finds 117440 in about 50 ms. A real program has 16 numbers, and the next step shows why its answer then has 16 octal digits: at least 8^15, about 3.5 × 10^13. On a generated program of that shape each try takes about 0.8 µs, so counting up to the answer would take one to a few years.
Step 2: build A one octal digit at a time
Look at what the example program does with A: it divides by 8 on every pass, and stops when A reaches 0. In octal, dividing by 8 drops the last digit. So an A with six octal digits makes six passes and prints six numbers, and after the first pass the program carries on exactly as if it had been started with A // 8. The output from A is one number followed by the output from A // 8.
Turn that round. The last number printed depends only on A’s top digit. The last two depend only on its top two digits, and so on. So find the top digit first: the one that makes the program print just the last number. Then try each of the 8 possible next digits, and keep one that makes it print the last two, and so on down to the full program. When no digit fits, back up and try the next digit one level up:
def lowest_a(program, target, b=0, c=0):
def search(prefix, i):
if i < 0:
return prefix
for digit in range(8):
a = prefix * 8 + digit
if a and list(run(program, a, b, c)) == target[i:]:
found = search(a, i - 1)
if found is not None:
return found
return None
return search(0, len(target) - 1)
def part2(text: str) -> int:
_, b, c, program = parse(text)
return lowest_a(program, program, b, c)
Every complete candidate has the same number of digits, and the digits are
tried from 0 up, so the first complete answer found is the lowest. The if a skips A = 0 at the top, because the answer must be positive. Each
candidate is checked by running the whole program, so whatever this returns
really is a program that prints itself.
On the example it takes 132 runs and about 0.2 ms. The clip shows a lot of backing up, and that comes from the example’s order of instructions: it divides A before printing, so each pass prints A’s second-lowest octal digit, not its lowest. A new digit is only tested one level further down, and the last digit isn’t tested at all: 345300 to 345307 in octal all work, and the search takes the 0.
The real inputs are reported (in the write-ups and forum threads I read) to be a slightly longer loop of the same kind: B = A mod 8, B ^= a constant, C = A » B, then B ^= C and B ^= another constant, A //= 8, print B mod 8, jump back while A isn’t 0 (the middle comes in different orders). B and C are rebuilt from A on every pass, and the output now depends on A’s lowest digits, so a wrong digit is rejected straight away. I couldn’t check that against a real input. I did generate programs of that shape with random constants, kept the ones that have an answer at all (122 of the 2,048 such programs do, about 1 in 17), and the search solves them in 0.4 to 3 ms, with 70 to 200 runs each.
The shape is what the search relies on. A program that changed A in some other way, or kept B or C from one pass to the next, could have a lowest answer that this search never reaches. That’s why the tests compare it with brute force on 150 random programs of the real shape, asking each for a short target output that brute force can still reach.
All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.