Twelve Days · day 10 · both parts
Day 10: Factory
Part 1 is a few lines once you see that a button never needs pressing twice. Part 2 looks like it needs an integer linear programming solver, which the standard library doesn’t have. The interesting part is that part 1, applied over and over to halved targets, gives the exact answer anyway.
The puzzle, in my words
Each line is a machine with a few buttons. Every button is wired to some positions, numbered from 0. Part 1: the positions are lights, all off at the start, and a press flips each light the button is wired to. Each machine comes with the pattern its lights should show. Find the fewest presses that produce it, and add those up over the machines.
In the example, the first machine has four lights that should read off, on, on, off, and six buttons wired to light 3; lights 1 and 3; light 2; lights 2 and 3; lights 0 and 2; and lights 0 and 1. Pressing the last two once each lights 1 and 2 (light 0 flips twice), so 2 presses. The other two machines need 3 and 2: 7 in all.
Part 1: a set of buttons
Step 1: a shortest path
Every light pattern is a state and every press moves to another one, so the fewest presses is a shortest path, and breadth-first search finds it: the first time the search reaches the goal, it got there in the fewest presses.
import re
from collections import deque
from math import inf
def machines(text: str):
"""Each machine as (diagram, buttons, targets)."""
out = []
for line in text.splitlines():
if not line.strip():
continue
diagram = re.search(r"\[([.#]*)\]", line)[1]
buttons = [
tuple(int(n) for n in group.split(",") if n)
for group in re.findall(r"\(([\d,]*)\)", line)
]
targets = tuple(int(n) for n in re.search(r"\{([\d,]*)\}", line)[1].split(","))
out.append((diagram, buttons, targets))
return out
def fewest(diagram, buttons):
goal = tuple(c == "#" for c in diagram)
start = (False,) * len(goal)
seen = {start}
queue = deque([(start, 0)])
while queue:
lights, presses = queue.popleft()
if lights == goal:
return presses
for button in buttons:
nxt = list(lights)
for i in button:
nxt[i] = not nxt[i]
nxt = tuple(nxt)
if nxt not in seen:
seen.add(nxt)
queue.append((nxt, presses + 1))
return inf
def part1(text: str) -> int:
return sum(fewest(diagram, buttons) for diagram, buttons, _ in machines(text))
A match object can be indexed, so re.search(...)[1] is the first group
(Python 3.6+). The targets at the end of each line are read now because part 2 needs them.
Step 2: subsets and XOR
Two things about flipping make the search unnecessary. Pressing a button twice changes nothing, and the order of presses doesn’t matter. So an answer is just a set of buttons, each pressed once, and the question is which is the smallest set that works.
Write the lights as a bitmask, light i as bit i, and each button too.
Then a press is ^ (XOR), and a set of buttons flips the XOR of all their
masks. itertools.combinations yields the sets of a given size, so trying
sizes 0, 1, 2, … in order finds a smallest one first:
from functools import reduce
from itertools import combinations
from operator import xor
def mask(indices) -> int:
return sum(1 << i for i in indices)
def fewest(diagram, buttons):
goal = mask(i for i, c in enumerate(diagram) if c == "#")
masks = [mask(b) for b in buttons]
for k in range(len(masks) + 1):
for combo in combinations(masks, k):
if reduce(xor, combo, 0) == goal:
return k
return inf
The 0 passed to reduce is the starting value, so the empty set (size 0)
gives 0, all lights off. With about a dozen buttons there are a few thousand
sets at most. On 160 generated machines of up to 10 lights and 13 buttons
this takes about 6 ms against 40 ms for the search, but the real gain is
the idea: an answer is a set, each button pressed at most once. Part 2 needs
it.
Part 2: counters instead of lights
Now ignore the lights. Each machine also lists a target for each position, and the positions are counters, all starting at 0, and a press adds 1 to each counter the button is wired to. Find the fewest presses that hit every target exactly. For the first machine that’s 10, and the three example machines need 10, 12 and 11: 33 in all.
Pressing twice no longer cancels, so the presses per button can be anything:
we need whole numbers x with A x = t (A says which button reaches which
counter) and the smallest total. That is an integer linear program.
Step 1: the same search
Breadth-first search still works: the states are tuples of counters, and since presses only add, a counter above its target can be dropped.
def presses(buttons, targets):
start = (0,) * len(targets)
seen = {start}
queue = deque([(start, 0)])
while queue:
counters, presses = queue.popleft()
if counters == targets:
return presses
for button in buttons:
nxt = list(counters)
for i in button:
nxt[i] += 1
nxt = tuple(nxt)
if nxt not in seen and all(c <= t for c, t in zip(nxt, targets)):
seen.add(nxt)
queue.append((nxt, presses + 1))
return inf
def part2(text: str) -> int:
return sum(presses(buttons, targets) for _, buttons, targets in machines(text))
It gives 10, 12 and 11 on the example, and it’s the version I trust for the tests. With targets in the hundreds, the states are every tuple below the targets that some presses can reach, and there are far too many. I stopped it after 60 seconds on a single generated machine of 8 counters with targets up to 160.
Step 2: take the odd part, halve the rest
Take any answer: button b pressed x_b times. Split each count into its
last bit and the rest, x_b = p_b + 2 * y_b with p_b = x_b % 2. The
buttons with p_b = 1 are a set, each pressed once, exactly as in part 1.
Whatever that set adds to the counters, the rest has to make up, and the rest
is twice y. So y is an answer for the targets that are left, halved.
That works backwards too: a set p that leaves every counter even and not
negative, plus any answer y for the halved targets, gives an answer
x = p + 2y. Every answer splits one way only, so nothing is lost or
counted twice, and the fewest presses for targets t is:
fewest(t) = min over sets p of len(p) + 2 * fewest((t - added(p)) / 2)
fewest(0, 0, ..., 0) = 0
The minimum is over the sets that add no more than t and have the same odd
counters as t. If no set fits, there is no answer. This is the exact
minimum, not an estimate: it comes from the one-way split, not from a
greedy choice. The targets halve at each level, so for targets up to 250 the
recursion is at most eight levels deep. Different sets often lead to the same
halved targets, and functools.cache (Python 3.9+) computes each of those
once.
from functools import cache
def subsets(buttons, n):
"""What every set of buttons, pressed once each, adds to the n counters."""
out = []
for k in range(len(buttons) + 1):
for combo in combinations(buttons, k):
added = [0] * n
for button in combo:
for i in button:
added[i] += 1
out.append((tuple(added), k))
return out
def presses(buttons, targets):
sets = subsets(buttons, len(targets))
@cache
def go(t):
if not any(t):
return 0
best = inf
for added, k in sets:
if all(a <= x and (x - a) % 2 == 0 for a, x in zip(added, t)):
half = tuple((x - a) // 2 for a, x in zip(added, t))
best = min(best, k + 2 * go(half))
return best
return go(targets)
go is defined inside presses, so each machine gets a new function and a
new cache. A cache shared between machines would be wrong, since its key is
only the targets. On the first machine, 3 5 4 7 has its odd counters at 0,
1 and 3. Pressing {3} and {0,1} once covers them and leaves 2 4 4 6, so the
next level is 1 2 2 3, and so on down to zeros, as in the clip: 2 presses,
then 2 worth 2 each, then 1 worth 4, for 10.
On 160 generated machines (4 to 10 counters, up to 13 buttons, targets up to 250) this takes 5.5 seconds. Most of that is testing every one of up to 8,192 sets at every call.
Step 3: look up only the sets that fit
Which counters a set leaves odd is a light pattern from part 1. Only the sets whose pattern is the same as the targets’ odd counters can work. So file the sets once, by that pattern as a bitmask, and each call looks up its own pattern instead of testing them all. Within a pattern, two sets that add the same amounts lead to the same halved targets, so keep only the smaller.
def presses(buttons, targets):
by_odd = {}
for added, k in subsets(buttons, len(targets)):
group = by_odd.setdefault(mask(i for i, a in enumerate(added) if a % 2), {})
group[added] = min(k, group.get(added, inf))
@cache
def go(t):
if not any(t):
return 0
odd = mask(i for i, x in enumerate(t) if x % 2)
return min(
(
k + 2 * go(tuple((x - a) // 2 for a, x in zip(added, t)))
for added, k in by_odd.get(odd, {}).items()
if all(a <= x for a, x in zip(added, t))
),
default=inf,
)
return go(targets)
min(..., default=inf) covers the case where no set fits, which is when a
target can’t be reached. The minimum is the same as step 2’s, only found
faster. On the same 160 generated machines it takes 0.27 seconds instead of
5.5. On 40 heavier ones (10 counters, 13 buttons, targets up to 250 each) it
takes 0.9 seconds, where step 2 takes 38.
The tests run both halving steps against the search on 300 random small
inputs of one to four machines each, with repeated buttons and zero targets,
and check that all three give inf on 50 machines whose targets can’t be
reached. At puzzle size the search can’t finish, so there the tests only
check that the two halving steps agree; that their answer is the minimum
rests on the argument above.
The sizes I generated (up to 10 counters and 13 buttons, targets up to 250)
are a recollection of real inputs, not something I could check; the one
real-size machine I saw quoted publicly had 6 counters, 8 buttons and
targets near 200. The code also assumes every machine can be solved. If one
couldn’t, the total would come out as inf.
All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.