Part One
Total distance traveled
- Puzzle answer
- 3,681
- Sample result ·
obbvb - 16
DAY 02 ADVENT OF CODE 2026
A farm that harvests thunder. A robot following colored waypoints. Six colors are all we need to measure a very long journey.
01 THE PUZZLE
The train's first stop collects thunder from passing storms. Away from the rumbling crates, the Elves have a quieter problem: their farm robot waters, fertilizes, and weeds as it follows a program of colored waypoints. How far will that program take it?
The track repeats roygbv: red, orange, yellow, green, blue, violet. Start on red, then move to the next waypoint matching each instruction. Red to orange costs 1. Red to red costs 6: the waypoint under the robot does not count.
For Part Two, rearrange the same instructions. Before each move, choose the remaining color whose next waypoint is furthest ahead. Use each instruction exactly once, then measure the journey using the same movement rules.
Read the original puzzle on Advent of CodePart One
obbvb1 + 3 + 6 + 1 + 5 = 16
Part Two
rybrybrybryb → rrbbyy = 32
02 THE INTERACTIVE LAB
The field keeps repeating. The robot only moves forward. Follow the original program in Part One, or rearrange the same instructions for the longest route in Part Two.
Distance /
Execution order
ROBOT marks the current position. NEXT marks the next destination.
Loading the sample walkthrough…
PERFORMANCE
Measure both parts on the current program. Part Two includes rearranging the instructions.
Each result is the per-run average from the middle of five batches sorted by total time. Timings exclude rendering and vary with your device, browser, and other running work. Small differences on short programs may be noise.
03 THE IMPLEMENTATION
Number the colors from 0 to 5. Subtract the current color's index from the destination's index, add 6, and take the remainder modulo 6. This gives the forward gap around one cycle. If that gap is 0, use 6 to reach the next occurrence.
Each instruction starts where the previous one ended, so its distance depends only on those two colors. Map instructions to jumps, then sum the jumps. There is no need to construct the repeating track: the calculation takes linear time in the program's length.
Moving to the current color costs 6, farther than any other next waypoint. If that color remains in the program, keep choosing it until its instructions are exhausted. Starting at red, the furthest other color is violet, then blue, green, yellow, and orange. Skipping empty buckets preserves that same order.
Count the instructions with Remeda, then rebuild them in r → v → b → g → y → o order. The counts preserve every instruction while the bucket order implements the choice made at each move. For rybryb, two reds, two blues, and two yellows become rrbbyy: 6 + 6 + 4 + 6 + 4 + 6 = 32. Feed that new program into the Part One distance calculation.
LINE 1
Remeda maps instructions to jumps, adds their distances, counts colors, and expands the counts into a new program. None of these operations changes the input.
import { countBy, flatMap, map, sumBy } from "remeda";LINES 3–4
The tuple fixes the order red, orange, yellow, green, blue, violet. Its indices run from 0 to 5. Derive the Color type from this same tuple so the types and calculation share one definition.
export const waypoints = ["r", "o", "y", "g", "b", "v"] as const;
export type Color = (typeof waypoints)[number];LINES 6–16
Ignore whitespace so a program can wrap across lines. Reject an empty program or any character outside the six colors. Return a read-only list of validated instructions.
export function parseProgram(input: string): readonly Color[] {
const program = input.replace(/\s+/g, "");
if (!program) throw new Error("Expected at least one waypoint instruction");
return map([...program], (color) => {
if (!waypoints.includes(color as Color)) {
throw new Error(`Invalid waypoint: ${JSON.stringify(color)}. Use r, o, y, g, b, or v.`);
}
return color as Color;
});
}LINES 18–21
Subtract the starting color index from the destination index. Adding six before taking the remainder keeps backward differences positive. A zero remainder means the same color: use six rather than standing still.
export function waypointDistance(from: Color, to: Color): number {
return (waypoints.indexOf(to) - waypoints.indexOf(from) + waypoints.length)
% waypoints.length || waypoints.length;
}LINES 23–30
Each move starts at the preceding instruction’s color; the first starts at red. Map every instruction to a new jump record and sum the distances. Returning both jumps and total lets the walkthrough show the same work as the command line.
export function analyzeProgram(program: readonly Color[]) {
const steps = map(program, (to, index) => {
const from = program[index - 1] ?? "r";
return { from, to, distance: waypointDistance(from, to) };
});
return { steps, total: sumBy(steps, ({ distance }) => distance) };
}LINES 32–34
The command-line solution only needs the total. Keep the route calculation in one place so the answer and explanation cannot use different rules.
export function totalDistance(program: readonly Color[]): number {
return analyzeProgram(program).total;
}LINES 36–42
A matching color always gives the largest possible move, six, so consume every remaining copy before changing color. From red, the next-best colors run backward around the cycle: violet, blue, green, yellow, orange. Count the original colors, then expand those six buckets into a new list. Missing colors contribute no instructions. This is the Elves’ specified greedy rule, not a search over permutations.
export function rearrangeProgram(program: readonly Color[]): readonly Color[] {
const counts = countBy(program, (color) => color);
const order = [waypoints[0], ...waypoints.slice(1).toReversed()];
return flatMap(order, (color) =>
Array.from({ length: counts[color] ?? 0 }, () => color)
);
}LINES 44–46
Rearrange the validated instructions, then pass the new list to the same Part One distance function. Counting and expansion both take linear time, with just six buckets to consider.
export function rearrangedDistance(program: readonly Color[]): number {
return totalDistance(rearrangeProgram(program));
}LINES 1–3
Import the shared functions and read input.txt next to this script. File access stays outside the pure calculation, and the website never imports this input file.
import { parseProgram, totalDistance } from "./base";
const input = await Bun.file(`${import.meta.dir}/input.txt`).text();LINE 4
Validate the program, calculate its total distance starting at red, and print the Part One answer. Run with bun run challenge-01.ts.
console.log(totalDistance(parseProgram(input)));LINES 1–3
Part Two uses the same private input as Part One. Import the shared parser and rearranged-distance wrapper rather than duplicating either calculation.
import { parseProgram, rearrangedDistance } from "./base";
const input = await Bun.file(`${import.meta.dir}/input.txt`).text();LINE 4
Validate the input, regroup its colors using the Elves’ greedy rule, and print the resulting distance. Run with bun run challenge-02.ts.
console.log(rearrangedDistance(parseProgram(input)));04 THE PUZZLE LOG
Published proofs, in order. New days will be added as they are solved.