Twenty-Five Days · day 24 · both parts
Day 24: Crossed Wires
Part 1 is a small simulation with three reasonable ways to get the order right. Part 2 is a different kind of puzzle: the circuit is a 45-bit adder with four pairs of wires crossed, and the way in is to know what an adder looks like. With no puzzle input of my own, everything in part 2 was tested on adders I generated, and I’ll say what that does and doesn’t prove.
The puzzle, in my words
Some wires start with a bit (x00: 1), and a list of gates combines two
wires with AND, OR or XOR into a third (x00 AND y00 -> z00). A gate fires
once both its inputs have values, and there are no loops. Read the wires
whose names start with z as a binary number, z00 the lowest bit.
In the small example the three gates give z02 z01 z00 = 100, which is 4.
The larger example has ten inputs and 36 gates and gives 0011111101000,
which is 2024.
Part 1: running the circuit
Step 1: sweep until everything has fired
Parse the starting values into a dict and the gates into
{output: (a, op, b)}, then sweep the list again and again, firing every
gate whose inputs are both known:
def parse(text: str):
top, bottom = text.strip().split("\n\n")
values = {}
for line in top.splitlines():
wire, bit = line.split(": ")
values[wire] = int(bit)
gates = {}
for line in bottom.splitlines():
a, op, b, _, out = line.split()
gates[out] = (a, op, b)
return values, gates
def z_number(values: dict[str, int]) -> int:
return sum(bit << int(wire[1:]) for wire, bit in values.items() if wire.startswith("z"))
def part1(text: str) -> int:
values, gates = parse(text)
waiting = dict(gates)
while waiting:
for out, (a, op, b) in list(waiting.items()):
if a in values and b in values:
if op == "AND":
values[out] = values[a] & values[b]
elif op == "OR":
values[out] = values[a] | values[b]
else:
values[out] = values[a] ^ values[b]
del waiting[out]
return z_number(values)
Every sweep fires at least one gate, because there are no loops, so it
ends. list(waiting.items()) takes a copy first, since deleting from a dict
while iterating over it raises a RuntimeError. The cost is one sweep per
level of the circuit in the worst case, which for a few hundred gates is
nothing.
Step 2: a topological order
What the sweeps are really looking for is an order in which every wire comes
after the two wires it’s computed from: a topological order. The standard
library has one, graphlib.TopologicalSorter (Python 3.9+), which takes
{node: its predecessors}. With it each gate fires exactly once, and the
if chain becomes a lookup in a dict of functions from operator:
import operator
from graphlib import TopologicalSorter
OPS = {"AND": operator.and_, "OR": operator.or_, "XOR": operator.xor}
def part1(text: str) -> int:
values, gates = parse(text)
order = TopologicalSorter({out: (a, b) for out, (a, _, b) in gates.items()})
for wire in order.static_order():
if wire in gates:
a, op, b = gates[wire]
values[wire] = OPS[op](values[a], values[b])
return z_number(values)
The input wires show up in the order too (they are predecessors with none of
their own), hence the if wire in gates.
Step 3: let recursion find the order
Or skip the order altogether. A wire’s value is its gate applied to its
inputs’ values, which is a recursive definition, and functools.cache
makes sure each wire is computed once:
from functools import cache
def part1(text: str) -> int:
values, gates = parse(text)
@cache
def value(wire: str) -> int:
if wire in values:
return values[wire]
a, op, b = gates[wire]
return OPS[op](value(a), value(b))
return sum(value(z) << int(z[1:]) for z in gates if z.startswith("z"))
Recursion depth is the only thing to check. In a 45-bit adder the top bit waits on a chain of 44 carries, about 90 nested calls, far below Python’s default limit of 1000; a test runs it on a generated adder with every bit set. All three steps take well under a millisecond on a generated circuit of the real size (222 gates), so this one is about which version reads best.
Part 2: four crossed pairs
The circuit is meant to be an adder: x and y are two 45-bit numbers and
the z wires should carry their sum. Four pairs of gates have had their
output wires swapped, and no gate is in two pairs. Find the eight wires and
list them sorted, joined by commas. It has to work for every x and y,
not just the starting values in the input.
The page’s example for this part is a different circuit: six AND gates meant
to compute x AND y bit by bit, with two pairs swapped (z05 and z00,
z02 and z01), so the answer is z00,z01,z02,z05. It shows the answer
format, but it isn’t an adder, and the methods that work on the real
circuit depend on it being one.
How an adder is built is the whole key. Bit 0 is two gates: x00 XOR y00
is z00, and x00 AND y00 is the carry. Every other bit i has five:
x XOR y(call it the half sum) andx AND y;- the sum,
half XOR carry, which isz_i; half AND carry;- the new carry, the OR of the two ANDs. The last carry is the top
z.
That’s 2 + 5 × 44 = 222 gates for 45 bits (the write-ups give 45 input
bits and a top wire z45; the gate count follows from that).
Step 1: brute force
The direct version: try every way to choose pairs disjoint pairs of gate
outputs, swap them, and keep the choice that makes the circuit compute the
right function for every x and y. The function is a parameter, because
the example wants AND and the real thing wants +:
from itertools import combinations
def simulate(values, gates) -> int | None:
"""The z number, or None if a swap made a loop."""
try:
order = list(TopologicalSorter({o: (a, b) for o, (a, _, b) in gates.items()}).static_order())
except ValueError: # graphlib.CycleError
return None
values = dict(values)
for wire in order:
if wire in gates:
a, op, b = gates[wire]
values[wire] = OPS[op](values[a], values[b])
return z_number(values)
def matchings(wires):
"""Every way to split an even number of wires into pairs."""
if not wires:
yield []
return
first, rest = wires[0], wires[1:]
for i, other in enumerate(rest):
for tail in matchings(rest[:i] + rest[i + 1 :]):
yield [(first, other), *tail]
def part2(text: str, pairs: int = 4, want=operator.add) -> str:
values, gates = parse(text)
bits = sum(w.startswith("x") for w in values)
zbits = sum(w.startswith("z") for w in gates)
tests = [(x, y) for x in range(1 << bits) for y in range(1 << bits)]
def inputs(x, y):
return {f"{c}{i:02d}": (n >> i) & 1 for i in range(bits) for c, n in (("x", x), ("y", y))}
found = []
for chosen in combinations(sorted(gates), 2 * pairs):
for matching in matchings(chosen):
fixed = dict(gates)
for p, q in matching:
fixed[p], fixed[q] = fixed[q], fixed[p]
if all(simulate(inputs(x, y), fixed) == want(x, y) % (1 << zbits) for x, y in tests):
found.append(matching)
if len(found) != 1:
raise ValueError(f"{len(found)} swap sets work, expected exactly one")
return ",".join(sorted(w for pair in found[0] for w in pair))
On the example, part2(text, pairs=2, want=operator.and_) tries 15 sets of
four wires times 3 ways to pair them, 45 choices, each against all 4,096
pairs of six-bit numbers (most fail on the first few), and returns
z00,z01,z02,z05 in about a tenth of a second. A swap can create a loop,
which is why simulate catches graphlib’s CycleError (a subclass of
ValueError) instead of hanging.
On the real circuit it’s hopeless: 8 wires out of 222 is
C(222, 8) ≈ 1.3 × 10¹⁴ choices, times 105 ways to pair them, about
1.35 × 10¹⁶, and one simulation of 222 gates takes about a third of a
millisecond here. Checking every x and y is hopeless too. So the brute
force is for the example and for tiny generated adders, where the tests use
it to check the other two steps.
Step 2: rules from the adder’s shape
Look at the list of jobs again. Each one fixes the gate that writes the wire
and the gates that read it: a z wire is written by an XOR (except the top
one, the last carry, written by an OR); an XOR that doesn’t read x and y
is a sum and must write a z; x AND y and half AND carry must feed an
OR; and so on. A wire that sits in the wrong place usually breaks one of
these, so flag every output that does. First a helper that refuses anything
without an adder’s gate counts (the AND example included):
def adder(text: str):
values, gates = parse(text)
bits = sum(w.startswith("x") for w in values)
ops = sorted(op for _, op, _ in gates.values())
if bits < 2 or ops != sorted(["XOR", "AND"] + ["XOR", "AND", "XOR", "AND", "OR"] * (bits - 1)):
raise ValueError("not shaped like a ripple-carry adder")
return bits, [(a, op, b, out) for out, (a, op, b) in gates.items()]
def part2(text: str) -> str:
bits, gates = adder(text)
last = f"z{bits:02d}"
readers: dict[str, set[str]] = {}
for a, op, b, _ in gates:
readers.setdefault(a, set()).add(op)
readers.setdefault(b, set()).add(op)
bad = set()
for a, op, b, out in gates:
reads = readers.get(out, set())
from_xy = a[0] in "xy"
first = {a, b} == {"x00", "y00"}
if out.startswith("z") and op != ("OR" if out == last else "XOR"):
bad.add(out) # z wires are sums (XOR), except the top one, the last carry
elif op == "XOR" and not from_xy and not out.startswith("z"):
bad.add(out) # a sum XOR must write a z wire
elif op == "XOR" and from_xy and first and out != "z00":
bad.add(out) # bit 0 has no carry in: its x XOR y is z00
elif op == "XOR" and from_xy and not first and "XOR" not in reads:
bad.add(out) # x XOR y feeds the sum XOR
elif op == "AND" and first and "XOR" not in reads:
bad.add(out) # bit 0's x AND y is the first carry
elif op == "AND" and not first and "OR" not in reads:
bad.add(out) # the other ANDs feed a carry OR
elif op == "OR" and out != last and "XOR" not in reads:
bad.add(out) # a carry feeds the next bit's sum XOR
return ",".join(sorted(bad))
This is the approach several write-ups take, it runs in a fraction of a
millisecond, and it never simulates anything. But it only looks at the kind
of gate on each side of a wire, so it can’t see a swap between two wires
with the same job. Swap z10 and z30, or the half sums of two different
bits, and every rule still holds: it returns nothing at all. (Two carries
can’t be swapped at all: that always makes a loop.)
On my generated adders this splits cleanly. When each of the four swaps stays inside one bit’s five gates, the rules found all eight wires in 300 out of 300 adders. Every allowed swap inside a bit changes some wire’s job: the ones that wouldn’t either make a loop (a bit’s half sum with its own carry out) or change nothing (the two ANDs that feed one OR). When the swaps can be anywhere, the rules got all eight in only 185 of 1,000. Several published solutions are built on these rules, which suggests real inputs only swap wires inside a bit, but that is a property of real inputs I couldn’t check here.
Step 3: walk the adder and fix it as you go
A swap moves only the outputs. Every gate still reads the same two input
wires, so a gate can be found by its op and its inputs: ("XOR", frozenset({"x07", "y07"})) is always bit 7’s half sum gate, whatever name
its output has now. That gives a walk from bit 0 upwards, trusting
everything below the current bit:
- The sum gate of bit
imust read the half sum and the carry. If no gate reads both names, one of them is wrong, and the XOR gate that reads the other one tells you the true name: swap it in. - That gate must write
z_i. If it writes something else, swap. - The carry OR must read
x AND yandhalf AND carry; fix it the same way. Its output is the carry into the next bit.
Sometimes both repairs are possible: the half sum’s name is read by some
other bit’s sum gate, and the carry’s name by this bit’s. Then prefer the
gate that fits bit i (it writes z_i; for the carry, the next sum gate
reads its output). And in case that guess is wrong, because two swaps hit
the same bit, the walk keeps a list of those choice points and part2 tries
the alternatives, depth first, until a repair uses exactly four swaps and
the repaired circuit adds:
import random
def adds(gates, bits: int, seed: int = 24) -> bool:
"""64 random sums at once: each wire's value is a 64-bit integer, one test per bit."""
rng = random.Random(seed)
values = {f"{c}{i:02d}": rng.getrandbits(64) for i in range(bits) for c in "xy"}
try:
order = TopologicalSorter({o: (a, b) for o, (a, _, b) in gates.items()}).static_order()
for wire in order:
if wire in gates:
a, op, b = gates[wire]
values[wire] = OPS[op](values[a], values[b])
except ValueError: # a loop
return False
carry = 0
for i in range(bits):
x, y = values[f"x{i:02d}"], values[f"y{i:02d}"]
if values.get(f"z{i:02d}") != x ^ y ^ carry:
return False
carry = (x & y) | (carry & (x ^ y))
return values.get(f"z{bits:02d}") == carry
class Stuck(Exception):
def __init__(self, message: str, choices: list[int]):
super().__init__(message)
self.choices = choices
def repair(text: str, picks: tuple[int, ...] = (), limit: int | None = None):
bits, gates = adder(text)
out = {(op, frozenset((a, b))): o for a, op, b, o in gates} # (op, inputs) -> output
swaps, choices, done = [], [], set()
def key(op, a, b):
k = (op, frozenset((a, b)))
if k not in out:
raise Stuck(f"no {a} {op} {b} gate", choices)
return k
def swap(bit, p, q):
if limit is not None and len(swaps) == limit:
raise Stuck(f"bit {bit}: more than {limit} swaps", choices)
kp = next(k for k, o in out.items() if o == p)
kq = next(k for k, o in out.items() if o == q)
out[kp], out[kq] = q, p
swaps.append((bit, p, q))
def pair_up(op, p, q, bit, fits):
"""Make p and q the inputs of one `op` gate, fixing whichever is wrong."""
if (op, frozenset((p, q))) in out:
return p, q
options = [] # (gate, [(wrong wire, its true name)])
for wire, other in ((p, q), (q, p)):
for k in out:
if k[0] == op and wire in k[1] and k not in done:
(true,) = k[1] - {wire}
if true[0] not in "xy" and true != other:
options.append((k, [(other, true)]))
if not options: # both are wrong: look for the gate that fits bit i
for k in out:
if k[0] == op and k not in done and fits(k) and min(k[1])[0] not in "xy":
t, u = sorted(k[1])
options += [(k, [(p, t), (q, u)]), (k, [(p, u), (q, t)])]
if not options:
raise Stuck(f"bit {bit}: no {op} gate reads {p} or {q}", choices)
options.sort(key=lambda opt: not fits(opt[0])) # the ones that fit first
n = len(choices)
choices.append(len(options))
_, fixes = options[picks[n] if n < len(picks) else 0]
for wrong, true in fixes:
swap(bit, wrong, true)
p, q = (true, q) if wrong == p else (p, true)
return p, q
if out[key("XOR", "x00", "y00")] != "z00":
swap(0, out[key("XOR", "x00", "y00")], "z00")
carry = out[key("AND", "x00", "y00")]
done |= {key("XOR", "x00", "y00"), key("AND", "x00", "y00")}
for i in range(1, bits):
x, y, z = f"x{i:02d}", f"y{i:02d}", f"z{i:02d}"
# The sum gate reads x XOR y and the carry, and writes z_i.
half, carry = pair_up("XOR", out[key("XOR", x, y)], carry, i, lambda k, z=z: out[k] == z)
if out[s := key("XOR", half, carry)] != z:
swap(i, out[s], z)
# The carry OR reads both ANDs; the next sum gate reads its output.
nxt = out[key("XOR", f"x{i + 1:02d}", f"y{i + 1:02d}")] if i + 1 < bits else None
def feeds_next(k, nxt=nxt) -> bool:
if nxt is None:
return out[k] == f"z{bits:02d}"
return ("XOR", frozenset((nxt, out[k]))) in out
both, mid = pair_up("OR", out[key("AND", x, y)], out[key("AND", half, carry)], i, feeds_next)
done |= {key("XOR", x, y), key("AND", x, y), s, key("AND", half, carry)}
done.add(c := key("OR", both, mid))
carry = out[c]
if carry != f"z{bits:02d}":
swap(bits - 1, carry, f"z{bits:02d}")
return swaps, {o: (min(ins), op, max(ins)) for (op, ins), o in out.items()}, choices
def part2(text: str, pairs: int = 4) -> str:
bits = adder(text)[0]
todo = [()]
while todo:
picks = todo.pop()
try:
swaps, fixed, choices = repair(text, picks, limit=pairs)
if len(swaps) == pairs and adds(fixed, bits):
return ",".join(sorted(w for _, p, q in swaps for w in (p, q)))
except Stuck as stuck:
choices = stuck.choices
taken = picks + (0,) * (len(choices) - len(picks))
for k in range(len(choices) - 1, len(picks) - 1, -1):
todo += [taken[:k] + (alt,) for alt in range(choices[k] - 1, 0, -1)]
raise ValueError("no repair with that many swaps makes it add")
It’s long, but each piece is one sentence of the plan above. Two Python
details: lambda k, z=z: ... binds the current z as a default argument,
the usual way to stop a function made in a loop from seeing the loop
variable’s later values (here it’s called straight away, so it would work
anyway, but the linter can’t know that). And adds checks 64 sums with a
single pass over the gates: Python’s integers are arbitrary-size, so
&, | and ^ on 64-bit values run 64 independent one-bit tests side by
side, one per bit position.
The last check is what makes the search safe. Whatever path the walk takes,
an answer is only returned if exactly four swaps make the circuit add 64
random pairs of 45-bit numbers, and limit cuts off any path that needs a
fifth swap (without it, one generated adder took a few seconds of searching).
On 1,000 generated adders with the four swaps anywhere, the walk found the
planted eight wires in 993; its first guess at every choice point was
already right in 971. The other 7 raised ValueError rather than give a
wrong answer. In the ones I looked at, two different swaps had hit both
inputs of the same gate (bit 8’s carry OR reading two wrong names, for
instance), where the names alone don’t say which gate is which and my
fallback for that case doesn’t always find the way. With the swaps inside a
bit, the kind real inputs seem to have going by the rule check’s record, it
was 300 of 300. A run takes about a millisecond (median 0.95 ms, worst 6 ms).
How part 2 was tested
The generator builds a correct 45-bit ripple-carry adder with random three-letter names for the inner wires, shuffles the gate lines and the two inputs of each gate, then swaps four pairs of outputs, refusing a swap that creates a loop (the puzzle promises none), one that changes nothing (two wires read by exactly the same gates, like the two ANDs that feed one OR), and any gate twice. The tests check every step on the examples where it applies (steps 2 and 3 refuse the AND circuit, which doesn’t have an adder’s gate counts), steps 2 and 3 on adders with swaps inside a bit, step 3 on adders with swaps anywhere, the two same-job swaps that step 2 misses, and step 3 against the brute force on 3-bit adders with two swaps.
That is evidence that the method does what it says on adders built the way the puzzle describes, not proof that it works on a real input: I didn’t run it on one.
All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.