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.
- 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.
Clockwise
R 0 O 1 Y 2 G 3 B 4 V 5Program rvgvo
Start at red. The robot has traveled 0 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.
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 for the initial red position and for the color of instruction i. For n instructions, start with a budget of six per instruction and subtract each backward penalty.
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.
- R0
- V1
- B2
- G3
- Y4
- O5
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.
| Order | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
rvgvo | 0 | 1 | 3 | 7 | 11 |
rvvgo | 0 | 1 | 1 | 3 | 5 |
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.
- 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 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.
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];- 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 lanes | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Current rank | 2 | 5 | 5 | 6 |
| Previous rank | 6 | 2 | 5 | 5 |
| Wrap bit | 1 | 0 | 1 | 0 |
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.
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.
- 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.
- Before
- 0.00138ms
- After
- 0.000693ms
- Speedup
- 2.0×
Benchmarks
| Workload | JavaScript wrap counter | Rust/Wasm SIMD |
|---|---|---|
| Bob’s input, fresh worker | 6.2 ms | 6.3 ms |
| Bob’s input, warm solve | 0.00138 ms | 0.000693 ms |
| 180,000 generated waypoints, warm solve | 0.217 ms | 0.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
- 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.