Original puzzle
Advent of Code 2026 Day 2

Fulminating Farmland

Turn the robot’s route into a wrap count, then score sixteen moves at once in Rust and WebAssembly.

2.0× faster than the one-pass JavaScript solver after warmup in Chromium. Timings

The puzzle

A robot starts at a red waypoint on a route whose colors repeat in the order roygbv. Each character in its program sends it forward to the next waypoint of that color. Adjacent waypoints are one step apart, so asking for the current color takes six steps.

  • Part 1 asks how far the robot travels when it follows the program in the given order.
  • Part 2 asks for the greatest distance it can travel after reordering the same instructions, using each one exactly once.

Start by walking the route

The first version moved one waypoint at a time until it reached the requested color. I used it for Part 1 as written. For Part 2, I sorted by backward distance from red, putting the instructions in rvbgyo order, then walked them again. The proof below explains why that order is optimal.

Sort and simulate Original JavaScript benchmark in Bun · Both parts on Bob’s input
Baseline
0.1444ms
Baseline JavaScript
const colors = "roygbv";

function sortProgram(input) {
  const program = input.trim();
  function walk(instructions) {
    let steps = 0;
    for (const color of instructions) {
      do steps++; while (colors[steps % 6] !== color);
    }
    return steps;
  }
  const reordered = [...program].sort((a, b) => (colors.indexOf(b) || 6) - (colors.indexOf(a) || 6));
  return [walk(program), walk(reordered)];
}

Take the example program rvgvo. Its first instruction sends the robot from red to the next red, a full lap of six steps. Later it goes from violet to green, passing red, orange, and yellow on the way. That move takes four steps. The dial shows how those moves build up over the whole program.

Program rvgvo

Start at red. The robot has traveled 0 steps.

The dot marks the robot’s position. A move can end where it started on the dial and still add six steps.

From violet to green, the robot could also find green two positions counterclockwise. That backward distance tells us how many steps to subtract from a full clockwise lap. Number the colors 0–5 in track order. For a move from a to b, call the backward distance the penalty δ. It is a − b reduced modulo six to a number from zero to five.

δ(a,b) = (a−b) mod6 s(a,b) = 6−δ(a,b)

If the color is repeated, the penalty is zero and the robot takes a full lap. For modular arithmetic and least nonnegative residues, see Lehman, Leighton and Meyer, Mathematics for Computer Science.

Score a route without walking it

The simulator asks about every waypoint it passes. The distance depends only on the two colors at the ends of a move. Write c0=0 for the initial red position and ci for the color of instruction i. For n instructions, start with a budget of six per instruction and subtract each backward penalty.

Score the original instruction order
D=6n− ∑i=1n δ(ci−1,ci)

Get Part 2 without sorting

Lay out the colors backward from red. Orange is in the example program, and it is five steps away on this line. Every order has to visit orange, so every order pays at least five in backward penalties. The question is whether five can be enough.

  1. R0
  2. V1
  3. B2
  4. G3
  5. Y4
  6. O5
Unroll one lap backward from red. Any route containing orange must reach position 5 or a later occurrence at 11, 17, and so on.

On this unrolled line, a move advances by its penalty. The position after the move is congruent modulo six to the destination’s backward distance from red. Reaching a color whose first occurrence is at distance h therefore costs at least h. If H is the farthest required backward distance, every route pays at least H.

Visit the required colors in increasing order of backward distance, keeping repeats together. For the example that gives rvvgo. Select Reordered in the route demo to compare the walks. Each move advances along the backward line by exactly the difference between the two positions. Those differences telescope to H, so this order meets the bound. An optimal route pays at most five, which keeps it within one backward lap. Its required backward distances must therefore be nondecreasing.

The greatest possible distance
H = max1≤i≤n δ(0,ci) Dmax = 6n−H
Order12345
rvgvo013711
rvvgo01135
The cells are cumulative penalties after each instruction. The original order wraps into a second backward lap on the return to violet. Its distance is 30 − 11 = 19. The reordered route stays on the first lap and reaches 30 − 5 = 25.

With those two formulas I could drop the sort and both simulated walks. The first one-pass version looked up each color in a string and used remainders to track the penalty for the original order and the largest backward distance.

One pass with modular arithmetic Both parts on Bob’s input
Before
0.1444ms
After
0.00876ms
Speedup
16.5×

Count wraparounds instead

The next question was whether every instruction needed a remainder. The raw difference ci−ci−1 points to the correct color. Add six whenever that difference is nonpositive so the move goes forward. The differences telescope from the first red to the final color. Only the number of wraparounds and the final color are needed.

D=cn+ 6∑i=1n [ci≤ci−1]

Solve both parts in one pass

For Part 1, count wraparounds and remember the final color. For Part 2, keep a six-bit set of all colors in the input. The colors just after red have the largest backward distances. Clear red’s bit, then find the least significant remaining bit to identify the color that sets the penalty. If only red appears, the penalty is zero.

A table indexed by character code decodes each instruction. It stores the colors as 1 through 6, so an empty entry can signal an invalid character. The comparison still detects every wrap. The final color is converted back to the formula’s zero-based index when computing Part 1. The JavaScript scan takes O(n) time and O(1) auxiliary space.

let previous = 1;
let wraps = 0;
let present = 0;
for (let i = 0; i < program.length; i++) {
  const next = COLOR_CODES[program.charCodeAt(i)];
  if (!next) throw new Error(`Invalid color at character ${i + 1}.`);
  wraps += Number(next <= previous);
  present |= 1 << next;
  previous = next;
}

const nonred = present & ~(1 << 1);
const firstNonred = 31 - Math.clz32(nonred & -nonred);
const penalty = nonred ? 7 - firstNonred : 0;
const fullLaps = 6 * program.length;
return [6 * wraps + previous - 1, fullLaps - penalty];
Wrap counter and character lookup Both parts on Bob’s input
Before
0.00876ms
After
0.000799ms
Speedup
11.0×

I tried a table that scored two adjacent instructions per lookup. Its small gain on Bob’s route disappeared on a generated route of 180,000 waypoints, where the table took 0.135 ms against 0.117 ms for the simpler loop. I kept the simpler version as the JavaScript fallback.

Score sixteen moves at once

The wrap counter reduces the route to adjacent comparisons and a minimum. That gives the processor more independent work to do at once. I first tested this in C, using a 128-bit WebAssembly vector to hold sixteen one-byte colors. Lay the same ranks out twice, with the second vector shifted by one lane so each color sits above its predecessor. Bringing in the last rank of the preceding block makes this work across block boundaries. A lane comparison produces a bit per wrap, then population count adds all sixteen bits. For Part 2, replace red with a sentinel rank of 7 and take the minimum rank across the block. The final penalty is seven minus the minimum across all blocks. WebAssembly specification, vector numeric instructions.

Vector lanes0123
Current rank2556
Previous rank6255
Wrap bit1010
The first four lanes of a block. Lane 0 takes its previous rank from the preceding block. Lane 2 counts the repeated color as a full lap.

The six ASCII letters have distinct indices under the map below. The XOR folds bits of the character together so that b and r can share a four-bit lookup table even though their low four bits match. A vector shuffle looks up all sixteen ranks at once. An inverse lookup recovers the ASCII letters, which must match the original bytes exactly for the program to be valid.

h(c)= (c⊕(c≫1))&15
const v128_t hash = wasm_v128_and(wasm_v128_xor(chars, wasm_u8x16_shr(chars, 1)), mask);
const v128_t rank = wasm_i8x16_swizzle(lookup, hash);
const v128_t previous = wasm_i8x16_shuffle(recent, rank,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
wraps += __builtin_popcount(wasm_i8x16_bitmask(wasm_u8x16_le(rank, previous)));

The JavaScript wrapper uses TextEncoder.encodeInto to copy the route directly into reusable WebAssembly memory. The kernel handles the last partial block with a short scalar loop. JavaScript also handles short inputs, browsers where SIMD is unavailable, and invalid input that needs a character index.

WebAssembly SIMD after warmup Both parts on Bob’s input
Before
0.000799ms
After
0.000142ms
Speedup
5.6×

Compiling and instantiating the embedded 717-byte module made the first solve take 0.48 ms in Bun. The warm figure includes encoding and scores both answers in the same pass.

Port the kernel to Rust

I first wrote a scalar Rust loop that matched each byte against the six colors. On a generated 180,000-move route it took 1.36 ms in a scratch Chromium test. The compiled Wasm had a br_table in the per-byte loop. Replacing the match with a byte lookup table took 0.223 ms, close to the JavaScript loop’s 0.183 ms on the same route.

The Rust SIMD port follows the same steps as the C kernel. The i8x16_swizzle intrinsic maps sixteen input bytes to their ranks, and the lane comparison and population count add all sixteen wraps. The short remainder goes through a byte loop. Rust calculates both answers inside the module and passes the result back in one call. Rust’s WebAssembly intrinsics.

let hash = v128_and(v128_xor(chars, u8x16_shr(chars, 1)), low_nibble);
let rank = i8x16_swizzle(lookup, hash);
let predecessor = i8x16_shuffle::<
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
>(recent, rank);
wraps += u64::from(i8x16_bitmask(u8x16_le(rank, predecessor)).count_ones());

On browsers without the required SIMD support, the runner uses the JavaScript wrap counter. It also uses that reference to locate malformed instructions.

Day 2 can work in place after the browser writes the route into linear memory. The first Rust module brought its standard allocator along and was about 16 KB. I gave the final module a scratch buffer backed by Wasm pages and grew it when the host had a longer route. The kernel, input buffer interface, and answer slots compile to 905 bytes together.

Score the route in Rust and Wasm SIMD JavaScript wrap counter to Rust/Wasm · Warm Chromium, both parts on Bob’s input
Before
0.00138ms
After
0.000693ms
Speedup
2.0×

Benchmarks

WorkloadJavaScript wrap counterRust/Wasm SIMD
Bob’s input, fresh worker6.2 ms6.3 ms
Bob’s input, warm solve0.00138 ms0.000693 ms
180,000 generated waypoints, warm solve0.217 ms0.0797 ms

The C SIMD version took 0.000665 ms in the same warm puzzle-input comparison. Both SIMD versions have similar warm costs. At the size of the puzzle input, fresh-worker time is measured in milliseconds and the solve itself in fractions of a microsecond.

The browser comparisons use Chromium 147 on a Threadripper 9970X, with Rust 1.100.0 targeting wasm32-unknown-unknown and simd128 enabled. Each figure is the median of nine measurements. Warm measurements batch complete solves, including input encoding when needed. Fresh measurements include worker startup, loading the solver on localhost, and receiving both answers. The earlier JavaScript and C milestones used Bun v1.4.5.

Start to finish Sort and simulate to Rust/Wasm · Warm Chromium, both parts on Bob’s input
Start
0.1484ms
Finish
0.000693ms
Speedup
214×

Run the solver

Paste a single program using r, o, y, g, b, and v. Your input stays in this browser.