The puzzle
A microwave starts with 0 on the display. Its buttons do arithmetic or edit the digits. [23] appends 23, [*9] multiplies by nine, and [/2] divides and rounds down. [1->9] replaces every 1 with a 9, [bksp] removes the last digit, and [oct] takes the octal digits and puts them back on the screen as a decimal number. For example, [oct] turns 9 into 11. Advent of Code, Rhythmic Factory.
- Part 1 asks for the sum of all distinct values reachable in at most three presses. The screen can go beyond four digits.
- Part 2 allows as many presses as you like. A press whose result would exceed 9,999 leaves the display where it was. Sum every distinct display you can reach under that rule.
The two rules can produce very different sets. With a lone [1234] button, Part 1 can reach 12,341,234 after two presses. In Part 2, the second press leaves the display at 1,234, so the only reachable values are 0 and 1,234.
Start with the button sequences
I tried every sequence of one, two, and three buttons for Part 1, replaying each from zero. For Part 2 I kept a JavaScript Set of displays and let the set grow as I iterated over it. Each button still did exactly what the puzzle said, including converting values to strings to edit digits.
- Baseline
- 2.675ms
Baseline JavaScript
function tryButtonSequences(input) {
const buttons = parseButtons(input);
function press(n, button) {
switch (button.op) {
case "append": return Number(String(n) + button.digits);
case "*": return n * button.value;
case "/": return Math.floor(n / button.value);
case "replace": return Number(String(n).replaceAll(button.from, button.to));
case "oct": return Number(n.toString(8));
case "bksp": return Number(String(n).slice(0, -1));
}
}
const short = new Set([0]);
for (const a of buttons) {
short.add(press(0, a));
for (const b of buttons) {
short.add(press(press(0, a), b));
for (const c of buttons) short.add(press(press(press(0, a), b), c));
}
}
const seen = new Set([0]);
for (const n of seen) {
for (const button of buttons) {
const next = press(n, button);
if (next < 10_000) seen.add(next);
}
}
const sum = (values) => [...values].reduce((total, value) => total + value, 0);
return [sum(short), sum(seen)];
}
The benchmark uses ordinary JavaScript numbers for these inputs. The browser’s fallback has an exact BigInt path for Part 1 when the values or the sum exceed the safe integer range.
Merge paths that reach the same display
Future presses depend only on the number on the screen. If I find 6 in two presses, getting back to 6 in three presses can offer no new options within Part 1’s budget. I keep the first visit and add each display to the sum exactly once.
Call the new displays after k presses and the displays seen so far . A button b is a function from a display to its next value. Start with zero in both sets. This is breadth-first search on a graph whose edges are generated by the buttons. Erik Demaine, Breadth-First Search.
[3][*2][bksp]- Start
0- 1 press
3- 2 presses
633- 3 presses
126366333
For Part 1 I stop after the third layer. For Part 2 I remove any transition outside 0–9,999 and keep going until there are no new displays. Leaving the display unchanged would send us back to a value we have already visited, so ignoring a canceled press is equivalent.
Give every four-digit display an address
The Part 2 profile pointed straight at the bounded search. It did almost all the work on this input. I replaced the hash set with a byte array indexed by the displayed number and stored the queue in a second array of 16-bit integers. That puts a hard ceiling of about 30 KB on those two buffers. Marking values when they enter the queue keeps every number from entering twice.
- Before
- 2.675ms
- After
- 1.481ms
- Speedup
- 1.81×
Port the loop to Rust
I first kept the same traversal order in Rust. It reads bytes from Wasm linear memory, does digit operations with integer arithmetic, and adds each discovered number as it appends it. I kept checked 64-bit arithmetic on the Part 1 path. Part 2 can use smaller values everywhere.
- Before
- 1.481ms
- After
- 0.4078ms
- Speedup
- 3.63×
Run one button over a whole frontier
The direct Rust port walked the queue one display at a time and picked a different handler for every button. Each layer is a rectangle of work, and we can read it in either order. I froze the current queue range and sent the whole range through one button at a time. Newly discovered displays go at the end, beyond that range, ready for the next frontier.
| Button | From 6 | From 33 |
|---|---|---|
[3] | 63 | 333 |
[*2] | 12 | 66 |
[bksp] |
The order of discovery within a layer can change, but the union of the new displays is the same. Each button now has a tight, specialized inner loop. An append uses a multiply and an add, a backspace is division by the constant ten, and the visited check determines whether the result gets queued.
let stop = search.end;
for button in &buttons {
match *button {
BoundedButton::Linear { scale, add } => {
search.batch(start, stop, |n| n * scale + add);
}
BoundedButton::Divide { reciprocal, shift } => {
search.batch(start, stop, |n| (n * reciprocal) >> shift);
}
BoundedButton::Replace(ref table) => search.batch(start, stop, |n| table.apply(n)),
BoundedButton::Octal => search.batch(start, stop, |n| {
if n < 4096 {
100 * octal_pair(n >> 6) + octal_pair(n & 63)
} else {
SCREENS as u32
}
}),
BoundedButton::Backspace => search.batch(start, stop, |n| n / 10),
}
}
start = stop;Rewrite two digits at a time
A digit replacement changes each position independently. Split a four-digit display at the hundreds place. The right half always occupies two places when the left half is present. Split 1005 into 10 and 05, and the replacement [0->7] gives 17 and 75. The standalone number 5 would stay 5. The padding rule is the whole reason for two tables.
- Leading group
1017- Two-digit suffix
0575
I build a 100-byte table T for ordinary numbers and a 100-byte table P for padded pairs. For displays shorter than three digits, look up the whole number in T. The same ordinary table handles the leading group of longer numbers.
Octal has a related split. A six-bit chunk contains two octal digits. Shift by three bits for the first digit and mask with seven for the second. Above 4,095 the octal representation is five digits long, so Part 2 can reject it before doing the conversion.
Divide with a multiply and a shift
The divisor belongs to the button and stays fixed throughout the search. For each divisor d, choose as the smallest power of two at least . Then precompute the rounded-up reciprocal m. The loop only needs (n * m) >> p. This is a bounded version of division by invariant integers. Granlund and Montgomery, Division by Invariant Integers using Multiplication.
Rounding up adds less than to the quotient. On this display that is less than , the smallest positive gap from to the next integer. So flooring gives the same result. Because S is less than 20,000 times d, the multiplier is at most 20,000 and its product with any four-digit input fits in 32 bits.
- Before
- 0.4078ms
- After
- 0.0730ms
- Speedup
- 5.58×
I also tried writing every candidate to the queue and advancing the tail only if the candidate was new. That eliminates the discovery branch at the cost of a write for every attempted transition. In a separate comparison on Bob’s input, the branchless loop took 0.109 ms to the branchy loop’s 0.082 ms. Most transitions in that run could avoid a queue write, so I kept the conditional store.
Count without searching when the buttons allow it
If the only operations are single-digit appends and optional backspace, the reachable positive numbers are precisely the decimal strings built from the available digits with a nonzero first digit. Backspace just returns to a prefix. The answer is a sum over place values.
Let q be the number of digits available, D their sum, and and the count and sum of the k-digit positive displays. Begin with the count of nonzero buttons and the sum D. Appending a digit makes q copies of every prefix, multiplies each copy by ten, and adds D across the suffixes of each prefix.
Add the sums for one through three digits for Part 1 and one through four for Part 2. If all ten digit append buttons are present, Part 2’s sum is 49,995,000 even with other buttons on the keypad. Every four-digit display is already reachable, and the limit prevents any extra buttons from adding to that set.
The first shortcut recognized a full display in Part 2, but still searched for the values reachable in three presses. The place-value sum removes that last search on the keypad with all ten digit buttons and backspace.
- Before
- 0.01035ms
- After
- 0.000296ms
- Speedup
- 35.0×
Rule out a batch of presses before trying them
The first Wasm version still computed the result of every growing button before checking the four-digit limit. On Bob’s keypad, 34,921 of 44,115 append, multiply, and octal applications overflow. Most of those checks can happen eight at a time, before doing any button arithmetic.
For a button that computes , the bound on its result gives a bound on its input. An octal press has the fixed cutoff 4,095, whose octal representation is 7777.
Eight 16-bit queue entries fit in one Wasm vector. An unsigned comparison marks the valid lanes, and a bitmask lets the loop visit only those entries. Each set bit still goes through the same visited check. The last few entries in a frontier use the scalar test. WebAssembly Core Specification, vector instructions.
let values = unsafe { v128_load(block.as_ptr().cast()) };
let mut valid = u16x8_bitmask(u16x8_le(values, limit));
while valid != 0 {
let lane = valid.trailing_zeros() as usize;
valid &= valid - 1;
self.discover(apply(self.queue[i + lane].into()) as usize);
}
Division and backspace have the opposite shape. A divisor d maps every display into the interval from zero through . Between layers I advance a pointer to the first unseen display. Once that pointer passes a button’s maximum output, its entire output interval has been seen. The button can sit out the rest of the search.
| Button | Output range | Next layer |
|---|---|---|
[bksp] | 0–999 | Skip |
[/17] | 0–588 | Skip |
[/2] | 0–4,999 | Keep |
I also folded the leading factor of 100 into the digit-replacement table. The lookup treats a missing leading group as zero and subtracts any padded tens digit from one-digit displays. I moved the sum out of the discovery loop into one pass over the finished queue. Every entry is unique, and even the full sum fits in a 32-bit integer.
- Before
- 0.0672ms
- After
- 0.0545ms
- Speedup
- 1.23×
I tried scanning backward from the unvisited displays when the queue was wide. That idea comes from direction-optimizing BFS, where the cheaper direction depends on the size of the frontier. Here the inverse of a digit replacement can have several candidates, and the reverse scan took 0.102 ms versus 0.0629 ms for the same run’s forward baseline. I also tried moving digits in 100-bit groups. Building the groups and unpacking the discoveries took longer than the table lookups on this input. Beamer, Asanović, and Patterson, Direction-Optimizing Breadth-First Search.
Benchmarks
| Workload | JS (typed) | Wasm v1 | Wasm SIMD |
|---|---|---|---|
| Bob’s input, fresh | 11.7 ms | 8.0 ms | 7.5 ms |
| Bob’s input, warm | 1.431 ms | 67.2 µs | 54.5 µs |
| Official example | 0.856 ms | 35.5 µs | 31.1 µs |
| Eight-button mixed keypad | 0.969 ms | 43.4 µs | 36.7 µs |
| Mixed keypad, 9,333 reachable | 1.125 ms | 91.4 µs | 65.2 µs |
| Ten digits and backspace | 0.675 ms | 415 ns | 397 ns |
All figures are for both parts on Chromium 147, on a Threadripper 9970X. Rust 1.100.0 compiled both modules for wasm32-unknown-unknown. The revised module enables simd128 and grew from 28,195 to 31,558 bytes. The first row gives medians of nine runs with a new worker, including loading the module from localhost and receiving both answers. All other rows give medians of nine warm batches and include parsing and input encoding where needed.
The new search saved 13 microseconds warm in this run and 15 in a repeat. Cold timing went the other way in the repeat, from 6.8 ms to 7.4 ms. Starting a worker and delivering the answers take much longer than the search.
With r reached displays and b buttons, the search does at most O(rb) transition work, with r capped at 10,000 for Part 2. The source bound and the covered output prefix let it skip many of those transitions. The digit-only shortcut skips the search entirely.
- Start
- 2.588ms
- Finish
- 0.0545ms
- Speedup
- 47.5×
Run the solver
Paste your keypad, with each button label in square brackets. Your input stays in this browser.