Twenty-Five Days · day 7 · both parts
Day 7: Bridge Repair
A puzzle where the first version is obvious and correct, and the interesting part is turning it round. Going forwards, every operator choice looks as good as any other. Going backwards from the answer, a multiplication can only be undone when the number divides the target, so most branches are cut before they start.
The puzzle, in my words
Each line is a target, a colon and some numbers. Put an operator in every gap between the numbers and evaluate strictly left to right, with no precedence and no reordering. If some choice of operators gives the target, the line counts. The answer is the sum of the targets that count.
With + and *, three of the example’s nine lines work: 190: 10 19 is
10 * 19, 3267: 81 40 27 is 81 + 40 * 27 (left to right, so 121 * 27) or
81 * 40 + 27, and 292: 11 6 16 20 is 11 + 6 * 16 + 20. The sum is 3749.
Part 1: plus and times
The animation shows the last step, which works backwards from each target.
Step 1: the first version
With k numbers there are k - 1 gaps and two operators, so 2 ** (k - 1)
choices. itertools.product("+*", repeat=k - 1) yields every one of them as a
tuple of characters. Evaluate each choice left to right and stop at the
first that hits the target:
from itertools import product
def equations(text: str) -> list[tuple[int, list[int]]]:
out = []
for line in text.splitlines():
test, rest = line.split(":")
out.append((int(test), [int(x) for x in rest.split()]))
return out
def part1(text: str) -> int:
total = 0
for test, nums in equations(text):
for ops in product("+*", repeat=len(nums) - 1):
value = nums[0]
for op, n in zip(ops, nums[1:]):
value = value + n if op == "+" else value * n
if value == test:
total += test
break
return total
split(":") leaves a space in front of the numbers; split() with no
argument splits on runs of whitespace and ignores it. A 12-number line has 2,048 choices, each evaluated from the start. On a
generated input of 850 lines of 2 to 12 numbers, it takes about 0.1 s.
Step 2: share the prefixes
Half of those choices start with + and half with *, and every choice
starting + * computes the same first two steps. Instead, keep the set of
values reachable so far and extend all of them by the next number at once.
A set also merges two choices that happen to reach the same value. And
since adding or multiplying positive numbers never makes a value smaller,
anything over the target can be dropped:
def part1(text: str) -> int:
total = 0
for test, nums in equations(text):
values = {nums[0]}
for n in nums[1:]:
values = {w for v in values for w in (v + n, v * n) if w <= test}
if test in values:
total += test
return total
About 30 ms on the same generated input. That pruning is the first place
the code relies on the numbers being positive: one 0 and * 0 would bring a
large value back down. The example has no zeros; that real inputs don’t
either is an assumption I couldn’t check.
Step 3: work backwards
The operator in the last gap acted on the last number. If it was +, the
value before it was test - n; if it was *, it was test / n, which only
exists when n divides test. So undo the last number, then the one before
it, and so on: a set of values that are still needed. When only the first
number is left, the line works if that number is in the set.
def undo(t: int, n: int):
if t > n:
yield t - n
if t % n == 0:
yield t // n
def possible(test: int, nums: list[int]) -> bool:
targets = {test}
for n in reversed(nums[1:]):
targets = {u for t in targets for u in undo(t, n)}
return nums[0] in targets
def part1(text: str) -> int:
return sum(test for test, nums in equations(text) if possible(test, nums))
t > n rather than t >= n because the value before a + is a result of
positive numbers, so it can’t be 0. The gain comes from the division: a
large target is divisible by few of the numbers, so the * branch usually
dies at once and a value has one child, not two. Going forwards, both
branches survive until they pass the target. In the example, 7290: 6 8 6 15
never needs more than four values in a row; on the generated input the sets
hold about 3 values on average (at most 30), against about 70 (at most
2,042) for step 2’s forward sets. About 3 ms, some thirty times faster than
step 1.
Part 2: gluing digits
Part 2 adds a third operator, concatenation, written ||: it joins the
digits of the two sides, so 15 || 6 is 156. Still left to right. Three
more example lines now work: 156: 15 6 (15 || 6), 7290: 6 8 6 15
(6 * 8 || 6 * 15, that’s 48 || 6 = 486, then * 15) and 192: 17 8 14
(17 || 8 + 14). The sum becomes 11387.
Step 1: three operators
The brute force takes one more branch. Going through a string is the obvious way to glue two numbers:
def part2(text: str) -> int:
total = 0
for test, nums in equations(text):
for ops in product("+*|", repeat=len(nums) - 1):
value = nums[0]
for op, n in zip(ops, nums[1:]):
if op == "+":
value = value + n
elif op == "*":
value = value * n
else:
value = int(str(value) + str(n))
if value == test:
total += test
break
return total
A 12-number line now has 3 ** 11 = 177,147 choices instead of 2,048.
On the generated input this took about 9 s, against 0.1 s for part 1.
Step 2: forward sets again
Part 1’s step 2 with the third operator. Concatenation never makes a positive value smaller either, so the same pruning holds:
def part2(text: str) -> int:
total = 0
for test, nums in equations(text):
values = {nums[0]}
for n in nums[1:]:
values = {w for v in values for w in (v + n, v * n, int(f"{v}{n}")) if w <= test}
if test in values:
total += test
return total
About 1 s. Better, but still slow, because the sets are much bigger than in part 1: on the generated input they hold about 1,200 values on average after a step, and up to 143,000, against about 70 and 2,042 with two operators.
Step 3: backwards, stripping digits
Concatenation can be undone too. If n has d digits, a || n is
a * 10**d + n. So it can only have been the last operator if t ends in
the digits of n, which is t % 10**d == n, and then the value before it was
t // 10**d. That’s one more yield in undo, and possible takes the
undo function as an argument so both parts share it:
def undo_with_concat(t: int, n: int):
yield from undo(t, n)
p = 10 ** len(str(n))
if t > n and t % p == n:
yield t // p
def possible(test: int, nums: list[int], undo) -> bool:
targets = {test}
for n in reversed(nums[1:]):
targets = {u for t in targets for u in undo(t, n)}
return nums[0] in targets
def part2(text: str) -> int:
return sum(test for test, nums in equations(text) if possible(test, nums, undo_with_concat))
t > n is needed here as well: 15 ends in the digits of 15, but stripping
them leaves nothing, which isn’t a number the line could have made. The
suffix test prunes like the division does: for a one-digit n, only about
one target in ten ends in its digit, and fewer still for longer ones, so the
search stays small: about 5 values on average, at most 64. That’s about 7 ms
on the generated input, against 9 s for step 1.
The tests run the three steps of each part on the example and on 200 random
inputs, and check that they agree. They also check 3240: 80 40, which ends
in 40 but leaves 32 rather than 80, so it must not count.
The generated input has 850 lines of 2 to 12 numbers of up to three digits, with targets below a quadrillion (10 ** 15). The timings are rough (best of a few runs on a busy machine), good for the order of magnitude only. All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.