Original puzzle
Advent of Code 2026 Day 5

Rhythmic Factory

Explore a microwave’s reachable displays, then turn strings and hash lookups into small integer loops in Rust and WebAssembly.

47.5× faster than the starting JavaScript solution after warmup in Chromium. Timings

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.

Replay the sequences Warm Chromium · Both parts on Bob’s input
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 Fk and the displays seen so far Sk. A button b is a function fb 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.

Build the next frontier from displays we’ve never seen
Fk+1= ⋃bfb (Fk)∖Sk
[3][*2][bksp]
Start
0
1 press
3
2 presses
633
3 presses
126366333
Each row contains the displays first reached at that depth. Backspacing from 33 returns to 3, whose first visit took one press.

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.

Use the display as an array index Sequence replay and Set to typed-array JavaScript · Warm Chromium, both parts on Bob’s input
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.

Move digit arithmetic into Wasm Typed-array JavaScript to scalar Rust/Wasm · Warm Chromium, both parts on Bob’s input
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.

ButtonFrom 6From 33
[3]63333
[*2]1266
[bksp]03
The loop handles one row at a time. The backspace row brings back two known displays, so neither enters the next frontier.

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.

[0->7]
Leading group
1017
Two-digit suffix
0575
Replacing zeros in 1005 yields 1775. The suffix keeps its zero before the rewrite.

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.

Rewrite a leading group and a padded suffix
n=100h+l, f(n)=100Th+Pl

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 S=2p as the smallest power of two at least 10000d. 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.

m=⌈Sd⌉ ⌊nd⌋=⌊nmS⌋

Rounding up adds less than n/S to the quotient. On this display that is less than 1/d, the smallest positive gap from n/d 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.

Batch the buttons and specialize the arithmetic Scalar to specialized Rust/Wasm · Warm Chromium, both parts on Bob’s input
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 Ck and Ak 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.

Ck+1=qCk Ak+1=10qAk+CkD

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.

Sum the decimal places instead of visiting displays Part 2 shortcut to place-value sums for both parts · Warm Chromium, all ten digits plus 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 ax+b, 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.

Precompute the largest valid input for a growing button
ax+b≤9999 ⇔ x≤⌊9999−ba⌋

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 ⌊9999/d⌋. 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.

ButtonOutput rangeNext layer
[bksp]0–999Skip
[/17]0–588Skip
[/2]0–4,999Keep
With 0–999 already reached, backspace and division by 17 have nothing new to add. Division by two still has a larger output interval.

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.

Filter eight displays at once and retire covered buttons First Wasm solver to revised Wasm solver · Warm Chromium, both parts on Bob’s input
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

WorkloadJS (typed)Wasm v1Wasm SIMD
Bob’s input, fresh11.7 ms8.0 ms7.5 ms
Bob’s input, warm1.431 ms67.2 µs54.5 µs
Official example0.856 ms35.5 µs31.1 µs
Eight-button mixed keypad0.969 ms43.4 µs36.7 µs
Mixed keypad, 9,333 reachable1.125 ms91.4 µs65.2 µs
Ten digits and backspace0.675 ms415 ns397 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 to finish Sequence replay to revised Rust/Wasm · Warm Chromium, both parts on Bob’s input
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.