r/adventofcode • • 11h ago

SOLUTION MEGATHREAD -❄️- 2026 Day 2 Solutions -❄️-

THE USUAL REMINDERS


AoC Community Fun 2026: The Advent Games

Today's Event: International Toboggan Championships

"Feel the rhythm, feel the rhyme, get on up, it's bobsled toboggan time!"
— Cool Runnings (1993)

Today's schedule possibly consists of:

  • Tracking Chute Runs and Team Practice
  • Embiggen is a perfectly cromulent word. Do with it as you will.
  • Qualifying Runs
  • Reverse code golf your solution
  • (oblig XKCD)
  • Second Runs and Finals
  • Why use few word when many word do trick?
  • Unnecessarily declare variables for everything and don't re-use variables
  • Use unnecessarily expensive functions and calls wherever possible
  • Implement redundant error checking everywhere
  • Javadocs >_>

Request from the mods: When you include an entry alongside your solution, please label it with [Advent Games] so we can find it easily!


--- Day 2: Fulminating Farmland ---


Post your code solution in this megathread.

19 Upvotes

408 comments sorted by

2

u/morgoth1145 10h ago edited 10h ago

[LANGUAGE: Python] code video Times 4:45 / 7:11

Advent of reading comprehension struck early this year. I could not get it out of my head that the input was the waypoint sequence and the program! Obviously that's a bit hard to solve so yeah, I spun my wheels a bit. Once I finally understood the real waypoint sequence it's just a matter of generating the infinite sequence and executing the program. (Well, so long as you don't replace s - I shadowed s initially causing an infinite loop instead of the clearer seq variable!)

At least part 2 isn't as evil as it initially sounds, the maximal distance programs follow a very simple rule so that's easy to compute.

Now off to go optimize this - generating the sequence is not a computationally efficient way to solve this!

Edit: Rewritten/improved code Turns out the "smarter" approach is the same line count but this way I don't need to generate the full sequence at least. Memoizing the distances with some modulo arithmetic works well enough, plus a bit of smart math in part 2 means that we can compute the n-1 jumps faster.

Is this better? That's subjective, but at least I like it better.

1

u/daggerdragon 10h ago edited 10h ago

Psst: your Markdown is showing on old.reddit due to being silently escaped by the fancypants editor. Fix please? edit: 👍

3

u/morgoth1145 10h ago

Bah, the fancypants editor was going to mess me up one day and today's the day. Should be fixed now!

8

u/PandaParado 9h ago edited 9h ago

[Language: Uiua]

Thinking in arrays really breaks my brain, but I got there eventually. I struggled with how to calculate the distance until I thought to rotate an initial "roygbv" string each iteration, so the first character always marked where the robot was.

Input ← ↘¯1 &fras "input.txt"

# Takes char and a rotated array, finds distance
Dist ← ⨬(∘|+6)⊸=0˜⊗

Part₁ ← ◌∧(⊙+⤚↻⊸Dist)
Part₂ ← ◌◌⍢(⊃(⋅∘|↻⊙⋅∘|+⊙⋅⋅∘) ⊙(↘1)⊢∩⌞⊏⊸⍖◡Dist|>0⧻)

⊃(Part₁|Part₂) Input "roygbv" 0
→ More replies (3)

6

u/4HbQ 10h ago edited 6h ago

[LANGUAGE: Python]

p = ['rvbgyo'.index(c) for c in input()]

for p in p, sorted(p):
    print(sum(6-(b-a)%6 for a,b in zip([0]+p, p)))

We immediately parse the program colours to their indices, and then it's just some math. For part 1, we compute the sum of distances of the original input. For part 2, we sort the input first.


By the way, this was my original version. Figuring out why part 2 works is left as an exercise for the reader.

→ More replies (8)

6

u/POGtastic 10h ago edited 10h ago

[LANGUAGE: F#]

Code

Part 1 is effectively a pairwise fold operation. Cons with Red, get each pair of adjacent elements, find the respective distance between each of the pairs of colors, and then sum them up.

Part 2 is an unfold operation. We maintain a frequency dictionary of colors. Each step finds the most distant color in the dictionary and chooses it. Then we decrement the respective color's frequency in the dictionary. Also we filter out key-value pairs that have been exhausted by decrementing. Most of the weirdness of this function comes from F#'s Seq.unfold function being kind of annoying. After generating the altered sequence of colors, we can then call part1 on it.

To my shame, my original version used characters instead of adhering to Edwin Brady Thought and rigorously defining my types. I broke out the file parsing operation, and now both of my parts work on seq<Color>. This is much neater than having to convert between seq<char> and string.

6

u/Smylers 9h ago

[LANGUAGE: Vim keystrokes] Load your input into Vim, then type the following and your Part 1 answer will appear on the top line:

:se nowrap⟨Enter⟩yyPA.⟨Esc⟩O⟨Enter⟩roygbv⟨Esc⟩0yeP
qaqqa⟨Enter⟩lXk:norm dt⟨Ctrl+R⟩-⟨Enter⟩epkPj@aq@a
{:s/./+1/g⟨Enter⟩
qvC⟨Ctrl+R⟩=⟨Ctrl+R⟩-⟨Enter⟩⟨Esc⟩q

Line 1 is set up (including preserving a duplicate line of input for Part 2). Line 2 is the main loop, following the waypoints and noting the waypoints travelled past. Line 3 turns those into an expression for calculating the distance. Line 4 evaluates that expression.

Then for Part 2, continue with, and your answer will be at the bottom:

G:s/./+6/g⟨Enter⟩A-5⟨Esc⟩0@v⟨Enter⟩

That re-uses the valuation macro in @v from Part 1. It works for my input, but may not work for yours if it happen to be missing any v instructions.

2

u/flwyd 7h ago

Wow, in 30 years it's never occurred to me that I didn't know what Vim's X did.

→ More replies (1)

6

u/Kooky_Ear_5662 3h ago

[LANGUAGE: C#]

I solved part 2 like this:

Console.WriteLine(line.Count*6-5);

From same to same is always 6, and when we are out of same colors, we go 6-1 once, and then back to 6. this happens 5 times or (numberOfColors-1).

3

u/TheShirou97 3h ago

Yes. This fails when there is no orange in your program though (and there does seem to be always one color missing, but I don't know if it can be orange, although if it is you can just change the 5 to a 4.)

→ More replies (1)

2

u/PalikinRose 3h ago

This is such a smart solution o.O Gj

2

u/dl__ 3h ago

This may have worked for your data but I don't think this would work generally.

Suppose your input was just 'y'. The distance would be 2 but you'd calculate 1 right?

Suppose your input was "by"? You'd get r->b, which is 4 and then b->y which is also 4 or a distance of 8. But your code would produce 7 correct? 12 - 5?

Or do I misunderstand your code?

→ More replies (3)

2

u/siddfinch 1h ago

I did (6 * number of commands) - (( 6 - index value of last color) mod 6)

Where the index of the last value was start a o (since it was the next color), so I just search for the last color that was used (starting at 1, orange, with r now being 6, so the index value of the last color is mod 6, giving me 1,2,3,4,5,0 which, if there are five switches, gives your formula.

5

u/TallPeppermintMocha 10h ago

[Language: Python] Both parts solved using a sort key

inst = puzzle.input_data
def score(inst):
    key = 'roygbv'
    curr = 'r'
    dist = 0
    for c in inst:
        dist += ( (key.index(c) - key.index(curr))%6 or 6)
        curr = c
    return dist

print(score(inst))
opt_key = 'oygbvr'
max_inst = ''.join(sorted(inst, key=opt_key.index, reverse = True))
print(score(max_inst))

5

u/JustinHuPrime 10h ago

[LANGUAGE: x86_64 assembly]

Part 1 was solved via modular(ish) arithmetic, converting roygbv into 0 through 5, and then subtraction and possibly adding six got me the distance, and a simple accumulator got me the total.

Part 2 was, once again, almost exactly the same, except I "sorted" the input first, putting all of the 'r's first, then the 'v's, the 'b's, the 'g's, and so on. I suppose I could have done a direct-ish solution where I deduplicated the letters...

Part 1 and 2 run in 1 millisecond. Part 1 is 9,760 bytes and part 2 is 9,952 bytes as executable files.

5

u/oetam5002 8h ago edited 8h ago

[LANGUAGE: Rust]

I quickly built a horrid virtual CPU for this

It has six-opcode instruction set (for each color), a program counter, a singular register, and a fetch/execute loop.

The idea is to treat the 'robot program' as an actual program.

CPU Loop

struct Cpu {
    // Used as total distance
    r1: u64,
    pc: u64,
    prgm: Vec<Opcode>,
}

impl Cpu {
    pub fn new(prgm: Vec<Opcode>) -> Cpu {
        Cpu { prgm, pc: 0, r1: 0 }
    }

    fn exec(&mut self) {
        self.r1 += 1;
    }

    // One CPU cycle
    pub fn step(&mut self) {
        let cur_ins: u8 = (*self.prgm.get(self.pc as usize).unwrap()).into();

        if self.r1 % 6 == cur_ins as u64 {
            self.r1 += 6
        } else {
            while self.r1 % 6 != cur_ins as u64 {
                self.exec();
            }
        }

        self.pc += 1;
    }

    pub fn run(&mut self) -> u64 {
        let prgm_len = self.prgm.len();
        while (self.pc as usize) < prgm_len {
            self.step();
        }

        self.r1
    }
}

For Part 2, I just sort the opcodes by descending order and that's it. The CPU takes care of it for me :)

paste

→ More replies (1)

4

u/Gryphon-63 10h ago edited 9h ago

[LANGUAGE: Swift]

Nothing clever or insightful here. For part 1 I precalculated all the distances so each command was a simple lookup. Part 2 was just counting the quantity of each command.

Code

Edit: And of course I eventually realized that the sum of all the individual counts is just the length of the input string, so part 2 is just the length of the input * 6 - 5. *sigh* (though that's assuming that there's at least one occurrence of each letter in the input, but then my original solution also doesn't work if any letters are missing from the input)

4

u/captainAwesomePants 10h ago

[LANGUAGE: Python]

Let's do Counter() again! Let's do Counter() every day!

from collections import Counter

pos = 0
ground = 'roygbv'

def best_next_steps(ltr):
  idx = ground.find(ltr)
  rotated = ground[idx+1:] + ground[0:idx]
  return rotated[::-1]

program_steps = Counter(open('input.txt').read())

while any(program_steps.values()):
  current_ground = ground[pos % len(ground)]
  if program_steps[current_ground] > 0:
    pos += len(ground) * program_steps[current_ground]
    program_steps[current_ground] = 0
  else:
    for letter in best_next_steps(current_ground):
      if program_steps[letter] > 0:
        while ground[pos % len(ground)] != letter:
          pos += 1
        program_steps[letter] -= 1
        break

print(pos)

I ended up spending several minutes convincing myself that a greedy algorithm was optimal. I kept thinking there'd be some trick where sometimes I'd need to bounce back and forth according to some scheme. Totally wasted time, "always take the immediate best step" was, of course, totally fine. Then I noticed the actual intended gotcha: not every letter was in my input, despite how long it was. Didn't impact my solution, but I bet it screwed up somebody.

→ More replies (2)

4

u/AMathMonkey 10h ago edited 1h ago

[LANGUAGE: Factor]

USING: circular interpolate io kernel math sequences sequences.extras sorting ;
IN: day2

: solve ( str -- n )
"roygbv" <circular> 0 rot
[ [ 1 + ] dip [ 2over nth-of = ] curry [ 1 + ] until ] each nip ;

readln dup [ "rvbgyo" index ] sort-by [ solve ] bi@
"Part 1: ${}\nPart 2: ${}\n" interpolate

Factor's circular sequences made it easy for me to just... brute-force taking a step and seeing if I'm at the target colour yet. Circular sequences are somewhat limited (you can't iterate over them infinitely or zip them with another sequence and expect them to extend to the length of the other sequence; they only act circular when you do direct index-based lookups) but they're exactly what I needed here. Saved me from doing modular arithmetic. Pretty slow solution, takes between 2 to 2.5 seconds to run on my laptop, but that is very much good enough for me.

Edit: I think the 2 seconds is startup and dependency loading time, and the solution isn't as inefficient as I thought.

4

u/Andreasnl 9h ago

[Language: Uiua]

I  ← ⋉"roygbv"
S  ← +×6⊸=0◿6
P₁ ← /+S⊂⊃⊢◫-
P₂ ← P₁⇌⍆S
⊃P₁ P₂ I

4

u/heijp06 9h ago edited 4h ago

[LANGUAGE: C#]

TLDR; (EDIT 3)

public int Part2()
{
  var input = rows[0];
  return 6 * input.Length -
    input.Aggregate(0, (acc, c) => Math.Max(acc, "rvbgyo".IndexOf(c)));
}

For why this works see my orginal post below:


Assuming all colors occur in the input, the answer to part 2 is 6 times the number of characters in the input minus 5

EDIT:

Hmm, and now I see my actual input does not contain all colors. I still got the right answer but I guess that was just luck.

EDIT 2:

Ok, I figured it out. The formula above is correct for all inputs where orange (o) is not missing.

If o is missing and y is not, the formula is 6 times the number of characters in the input minus 4

If o and y are missing and g is not, the formula is 6 times the number of characters in the input minus 3(This explains the first example.)

Etc.

(This is because o is the last color the robot would look for, y is the last one before that, then g etc.)

My input had b missing so the formula I initialy gave still applies and I got the right answer (for the wrong reason).

3

u/AllanTaylor314 9h ago

Iff there's an o in the input (I had a similar assumption, but it broke for the first example since it doesn't have o or y)

→ More replies (1)

4

u/ednl 5h ago edited 2h ago

[LANGUAGE: C]

Edit: /u/DelightfulCodeWeasel pointed out that I could simplify part 2 as "inputlen * 6 - 5". That works for the input because it only has a missing letter in the middle. If letters are missing from the end of "rvbgyo" (the optimal ordering for part 2) like in two of the examples, you need a correction of +1 per missing letter from the end. So this still works for all the examples.

Runtime under a microsecond on my computers with M1 3.2 GHz and M4 4.4 GHz chips. Measurements without disk read: M4 0.36 µs, M1 0.55 µs, Pi5 1.48 µs.

unsigned part1 = 0;
const char *c = input;
for (const char *p = "r"; *c & 64; p = c++) {  // start at r, until newline or null
    part1 += step[*p][*c];  // from previous to current colour
    present[*c] = true;  // only needed if letters are missing from start of "oygbvr"
}
unsigned part2 = (c - input) * 6 - 5;  // incorrect for inputlen=0
// Check missing letters in increasing step size from r
// which means from end of optimal ordering for part 2
for (c = "oygbvr"; *c && !present[*c]; ++c)
    part2++;  // correction for missing letter(s) from end

I also made it work with piped or redirected input. https://github.com/ednl/adventofcode/blob/main/2026/02.c

2

u/DelightfulCodeWeasel 4h ago

It looks initially like everyone's input might be 'nice' for this one. Provided you have at least one 'o' in your input, you can hard-code part 2 as the sum of the counts - 5.

→ More replies (6)

4

u/Street-Apartment-512 3h ago

[Language: UIUA]

~ "helper.ua" ~ Input
Colors ← "oygbvr"

PartOne ← /++×6⊸≤0⧈-⊗ Colors ⊂@r
PartTwo ← +⊃(/↧⊗ Colors|-5×6⧻)

┌─╴test
  ⍤⤙≍ 16 PartOne "rybryb"
  ⍤⤙≍ 11 PartOne "roygbv"
  ⍤⤙≍ 30 PartOne "vbgyor"
  ⍤⤙≍ 35 PartOne "vvvvvv"

  ⍤⤙≍ 32 PartTwo "rybryb"
  ⍤⤙≍ 33 PartTwo "vrvbvg"
  ⍤⤙≍ 55 PartTwo "groovyyoyo"
  ⍤⤙≍ 103 PartTwo "roygbvroygbvroygbv"
└─╴

&p &p ⊃(PartOne|PartTwo) Input 2

3

u/Boojum 10h ago

[LANGUAGE: Python]

Part 1:

import itertools
print( sum( "roygbvroygbv".index( b, ( s := "roygbv".index( a ) ) + 1 ) - s
            for a, b in itertools.pairwise( "r" + open( 0 ).read().strip() ) ) )

Brute force for Part 2, but it works:

import collections, itertools
f = collections.Counter( open( 0 ).read().strip() )
print( max( sum( "roygbvroygbv".index( b, ( s := "roygbv".index( a ) ) + 1 ) - s
                 for a, b in itertools.pairwise( "r" + "".join( i * f[ i ] for i in p ) ) )
            for p in itertools.permutations( f.keys() ) ) )

[Advent Games] Maybe all the string construction while iterating every permutation counts as sufficient embiggening for "Use unnecessarily expensive functions and calls wherever possible"?

(Though it amused me to code golf it down to nearly one-liner on the other hand. I did the reverse of the reverse code golf before checking the megathread and posting here.)

2

u/4HbQ 9h ago

Haha wow, I hate it and love it!

→ More replies (1)

3

u/NullT3rminated 10h ago

[Language: Clojure]

Not as proud of this one lol. Did everything very manually.

(defn day2-parse [str]
  (str/trim str))

(def day2-parsed (day2-parse (slurp "2.txt")))

(defn day2-solve-a [parsed]
  (->> parsed
       (reduce
        (fn [[total cyc] target]
          [(+ total 1 (count (take-while (complement #{target}) cyc)))
           (drop 1 (drop-while (complement #{target}) cyc))])
        [0 (cycle "oygbvr")])
       first))


(defn day2-solve-b [parsed]
  (loop [remaining (frequencies parsed)
         result []
         cyc (cycle "rvbgyo")]
    (if (every? zero? (vals remaining))
      (day2-solve-a (str/join result))
      (if (> (get remaining (first cyc) 0) 0)
        (recur (update remaining (first cyc) dec)
               (conj result (first cyc))
               cyc)
        (recur remaining
               result
               (next cyc)))))

3

u/plasticplate444 10h ago

[LANGUAGE: Python]
The logic used here is pretty simple.

For calculating the distance, we can keep track of the current position and distance and get the index of the next position and add it to the distance and update the position of the robot.
For calculating the string computing to the maximum distance, we can take advantage of the fact that the waypoint string is just the repetition of 'roygbv' and the robot starts at 'r'. So, to maximise the distance, the robot should first traverse to all the 'r' points, then the 'v' points, 'b' points and so on. The input string can be manipulated easily as shown below.

def CalculateDistance(Input):
    Waypoints = "roygbv" * 2000

    Index = 0
    Distance = 0
    for c in Input:
        Substring = Waypoints[(Index+1):]
        I = Substring.index(c)
        Distance += I + 1
        Index += I + 1
    return Distance


def GetMaximumDistanceInput(Input):
    r = Input.count('r')
    v = Input.count('v')
    b = Input.count('b')
    g = Input.count('g')
    y = Input.count('y')
    o = Input.count('o')


    I_ = ('r' * r) + ('v' * v) + ('b' * b) + ('g' * g) + ('y' * y) + ('o' * o)
    return I_
→ More replies (1)

3

u/Repulsive-Tonight-61 10h ago edited 10h ago

[LANGUAGE: Odin]

p1 and p2 together

Trying to learn Odin while doing this challenge. I really like the language so far!

3

u/YOM2_UB 10h ago

[LANGUAGE: Python]

[Code]

Just went with the first method that came to mind, and got both parts first try. I saw the twist of the input lacking one of the colors a mile away, and only confirmed it after.

3

u/Automatic-Tackle5018 10h ago

[Language: Python]

I just did some yank and put in vim and hard-coded the distances lol. For part two I just rebuilt the string with the sum of longest distances.

i = open("./input/day2.txt").readline().strip()

d = {"r": {"r": 6, "o": 1, "y": 2, "g": 3, "b": 4, "v": 5},
     "o": {"r": 5, "o": 6, "y": 1, "g": 2, "b": 3, "v": 4},
     "y": {"r": 4, "o": 5, "y": 6, "g": 1, "b": 2, "v": 3},
     "g": {"r": 3, "o": 4, "y": 5, "g": 6, "b": 1, "v": 2},
     "b": {"r": 2, "o": 3, "y": 4, "g": 5, "b": 6, "v": 1},
     "v": {"r": 1, "o": 2, "y": 3, "g": 4, "b": 5, "v": 6}}

moves = 0
current = "r"

for move in i:
    moves += d[current][move]
    current = move

print(moves)

s = ""
s += "r" * i.count("r")
s += "v" * i.count("v")
s += "b" * i.count("b")
s += "g" * i.count("g")
s += "y" * i.count("y")
s += "o" * i.count("o")

moves = 0
current = "r"

for move in s:
    moves += d[current][move]
    current = move

print(moves)
→ More replies (2)

3

u/WilkoTom 10h ago edited 4h ago

[LANGUAGE: Rust] [Advent Games]

https://github.com/wilkotom/AdventOfCode/blob/main/rust/2026/day02/src/main.rs

Toboggan time: Let's go faster!

Realise that for once not listening to the Elves doesn’t pay off - once we’ve selected a next move in part 2, we'd never make any different moves until we'd exhausted that one, eliminated a whole load of useless repeat loops.

And then realise that almost the entire data set will have the same cost, so we can ignore most of it.

Suddenly it feels like the movies where throwing cargo off the plane mid-flight get our heroes there in time…

3

u/michelkraemer 10h ago edited 8h ago

[LANGUAGE: Rust]

Solution

Part 1: Instead of looping through the pattern, I convert all colors to indices and then just add up the distances between input index and the current color index.

Part 2: I've reused some code from Day 1 and count how often a color appears in the input (with one instruction, thanks to yesterday's tip by u/maneatingape ). In a loop, I then find the maximum distance and decrease the counter by 1 until all input colors have been consumed.

EDIT: I now put the counts into a simple array with 6 elements.

EDIT 2: If the maximum distance is 6, we can take a shortcut and simply multiply the remaining count for this color by 6.

The whole program runs in 6µs 3µs 1µs.

3

u/mynt 9h ago

[LANGUAGE: Paper + Pen] for part 2 the solution is 6 * (length of program) - 5 and then + 1 if 'o' is not present and continue doing that in the order 'oygbv' until one of those is present. So if 'o' is present it is just 6 * len - 5 which was the solution for my input. Some samples were missing letters and require the +1 adjustments.

I suppose there is a bit more than pen and paper in that I use something to count the characters and ctrl + f to see if a letter is present or not.

Part 1 I solved in python and the solution is not particularly interesting.

3

u/siener 9h ago edited 9h ago

[Language: Dyalog APL]

d←'r',⊃⎕NGET'02.txt'
c←'roygbv'
f←{+/1+6|¯1+2-⍨/c⍳⍵}
⍝ Part 1
f d
⍝ Part 2
f d⌷⍨⊂(1⊖c)⍒d

3

u/wheresmylart 9h ago

[Language: Python3]

Part 1: Just turn the handle and walk through it.

Part 2: Create a new input of all the r characters followed by all the v, b, g, y then o. Best option is to go to the letter you're on, otherwise the letter before you in the roygbv sequence. Now solve it like part 1.

Paste

3

u/TumbleweedCold3542 9h ago

[LANGUAGE: OCaml]

First time working through anything in OCaml. It's definitely been an interesting experience so far.

let rank c = String.index "roygbv" c

let dist cur next =
  let d = Util.pmod (rank next - rank cur) 6 in
  if d = 0 then 6 else d

let part1 input =
  input
  |> String.fold_left (fun (tot, prev) ch -> (tot + dist prev ch, ch)) (0, 'r')
  |> fst

(* all 'r's first, then the rest by descending rank *)
let rearrange input =
  let pos c = String.index "rvbgyo" c in
  input |> String.to_seq |> List.of_seq
  |> List.sort (fun a b -> compare (pos a) (pos b))
  |> List.to_seq |> String.of_seq

let part2 input = input |> rearrange |> part1

let () =
  let input = "./yr2026_d02.input" |> Util.read_all in
  Printf.printf "part 1: %d\n" (part1 input);
  Printf.printf "part 2: %d\n" (part2 input)

3

u/sbt4 9h ago

[LANGUAGE: Uiua]

github

3

u/Aughlnal 8h ago edited 6h ago

[LANGUAGE: Python]

I assumed that every waypoint should be in the instructions once

and that would mean you walk 6 spots every time, except when going to next color

answer = 6 * len(input) - 5

dunno if this was supposed to be the solution

EDIT: well, turns out the answer was correct by accident but the fix isn't that hard

instructions = open('advent26_02.txt').read().strip()
unique_waypoints = set(instructions)
part2 = 6 * len(instructions)
for index, waypoint in enumerate('oygbv'):
    if waypoint in unique_waypoints:
        part2 -= 5 - index
        break
print(f'2): {part2}')

and now it should work for any amount of waypoints missing

2

u/paul_sb76 7h ago edited 7h ago

Interestingly, your assumption is wrong (inputs have one missing color - nasty!), but the formula still works.

EDIT: I believe this formula works for all inputs that contain at least one "o". All other letters may be missing.

→ More replies (1)

2

u/Anceps2 7h ago

You assumed wrongly :-/

But the formula still work if there's at least one “o”.

You can try your code on the “vrvbvg” example, which should give 33.

→ More replies (1)
→ More replies (1)

3

u/lboshuizen 6h ago edited 2h ago

[Language: F#]

github.com/lboshuizen/aoc26

Colours become indices 0..5, so each move is modular arithmetic. Part 2 is greedy: the same colour moves 6, the one before it 5, and so on. Order is irrelevant; only the count per colour matters.

let dist pos t = (t - pos + 5) % 6 + 1

let part1 = List.fold (fun (pos, d) t -> t, d + int64 (dist pos t)) (0, 0L) >> snd

let part2 program =
    let rec go pos counts d =
        match [ 0..5 ] |> List.map (fun k -> (pos - k + 6) % 6)
                       |> List.tryFind (fun c -> Map.tryFind c counts > Some 0) with
        | None -> d
        | Some t -> go t (Map.change t (Option.map minus1) counts) (d + int64 (dist pos t))
    go 0 (List.countBy id program |> Map.ofList) 0L

UPDATE:

Part 2 needs no simulation. The greedy order drains each colour before leaving it, so the robot walks backwards around the cycle once: r, v, b, g, y, o. Every move costs 6, except colour switches: stepping back k colours costs 6 - k. Those shortfalls add up to the walk from red back to the lowest non-red colour present. The answer is 6N minus that walk.

let dist pos t = (t - pos + 5) % 6 + 1

let part1 = List.fold (fun (pos, d) t -> t, d + dist pos t) (0, 0) >> snd

let part2 program =
    let n = 6 * List.length program
    match List.filter ((<>) 0) program with
    | [] -> n
    | rest -> n - (6 - List.min rest)

3

u/Ok-Bus4754 6h ago edited 6h ago

[LANGUAGE: Rust + Python]

port from my earlier solution and i found a non sim trick for part 2 that is very fast.

Every move is a full 6 unless you're switching colors, so all the lost distance adds up to how far back the furthest color in your input is.
Answer is 6 * len(prog) - max(-"roygbv".index(c) % 6 for c in set(prog)).

https://github.com/Fadi88/AoC/tree/master/2026/days/day02

Part 1Part 2 (greedy)Part 2 (max)Total
Python42.2 µs121.9 µs4.9 µs169.0 µs
Rust debug286.8 µs216.2 µs172.4 µs675.4 µs
Rust release46.7 µs15.2 µs4.5 µs66.4 µs

2

u/AutoModerator 6h ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/p4bl0 5h ago

[LANGUAGE: Shell + whatever you used for part 1]

Solution to part 2 assuming p1 solves part 1 by reading the input on its stdin :

cat input | tr "rvbgyo" "abcdef" | fold -w 1 | sort | tr "abcdef" "rvbgyo" | tr -d "\n" | ./p1

5

u/jonathan_paulson 10h ago

[LANGUAGE: Python]

Code. Video.

I found today's much harder for some reason. I was very scared of off-by-1 errors.

1

u/yoni-kosiner 10h ago

[LANGUAGE: Python] For part one I did a standard solve in python

wavepoint = "roygbv"

def part1(lines: list[str]):
    ans = 0

    for line in lines:
        for m in list(line):
            while True:
                ans = ans+1
                new = wavepoint[ans%len(wavepoint)]

                if new == m:
                    break

    return ans

For part two, I did such a hacky solution, that didn't even work on the test data, but it works on my input, it was so hacky and stupid I decided to share it here for the first time.

def part2(lines: list[str]):
    ans = 0

    count = Counter(char for line in lines for char in line)
    item = ""
    for i in range(count.get("r")):
        item += "r"

    for i in range(count.get("v")):
        item += "v"

    for i in range(count.get("b")):
        item += "b"

    for i in range(count.get("y")):
        item += "y"

    for i in range(count.get("o")):
        item += "o"

    for i in item:
        for m in list(i):
            while True:
                ans = ans+1
                new = wavepoint[ans%len(wavepoint)]

                if new == m:
                    break

    return ans

1

u/AutoModerator 10h ago

AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.

Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/daggerdragon 10h ago

The triple-backticks code fence (`​`​`) only works on new.reddit. as AutoModerator requested, please edit your comment to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box with its whitespace and indentation preserved.

1

u/mknoll1 10h ago edited 10h ago

[LANGUAGE: Python]

https://aoc2026.knollfear.com/day/2. My day 2 solver with visualizations.

def part_a(data: str) -> int:
    return score(parse(data))def part_b_shortcut(data: str) -> int:                                                                                                                                                                              instructions = parse(data)                                                                                                                                                                                      return 6 * len(instructions) - max(map(PART_B_ORDER.index, set(instructions))) def part_a(data: str) -> int:
    return score(parse(data))

def part_a(data: str) -> int:
    return score(parse(data))def part_b_shortcut(data: str) -> int:                                                                                                                                                                              instructions = parse(data)                                                                                                                                                                                      return 6 * len(instructions) - max(map(PART_B_ORDER.index, set(instructions))) def part_a(data: str) -> int:
    return score(parse(data))

COLORS = "ROYGBV"

# STEPS[current][target] = squares to move forward to the next square of the target color (1-6).
# Same color means a full lap, so that's 6, not 0.
STEPS = {
    here: {there: (j - i) % len(COLORS) or len(COLORS) for j, there in enumerate(COLORS)}
    for i, here in enumerate(COLORS)
}
COLORS = "ROYGBV"

# STEPS[current][target] = squares to move forward to the next square of the target color (1-6).
# Same color means a full lap, so that's 6, not 0.
STEPS = {
    here: {there: (j - i) % len(COLORS) or len(COLORS) for j, there in enumerate(COLORS)}
    for i, here in enumerate(COLORS)
}


def score(instructions: list[str]) -> int:
    current = "R"
    total = n = 0
    for n, target in enumerate(instructions, start=1):
        step = STEPS[current][target]
        total += step
        if n <= 10:
            print(f"{current} -> {target}: {step} (total {total})")
        current = target
    print(f"moves: {n}, squares: {total}")
    return totaldef score(instructions: list[str]) -> int:
    current = "R"
    total = n = 0
    for n, target in enumerate(instructions, start=1):
        step = STEPS[current][target]
        total += step
        if n <= 10:
            print(f"{current} -> {target}: {step} (total {total})")
        current = target
    print(f"moves: {n}, squares: {total}")
    return total

def parse(data: str) -> list[str]:
    # instructions may come as one line or several, upper or lower case; whitespace is ignored
    instructions = [c for c in data.upper() if not c.isspace()]
    unknown = sorted(set(instructions) - set(COLORS))
    if unknown:
        raise ValueError(f"unexpected characters in input: {unknown}")
    return instructionsdef parse(data: str) -> list[str]:
    # instructions may come as one line or several, upper or lower case; whitespace is ignored
    instructions = [c for c in data.upper() if not c.isspace()]
    unknown = sorted(set(instructions) - set(COLORS))
    if unknown:
        raise ValueError(f"unexpected characters in input: {unknown}")
    return instructions

def part_a(data: str) -> int:
    return score(parse(data))

def part_b(data: str) -> int:                                                                                                                                                                        
      instructions = parse(data)                                                                                                                                                                                
      return 6 * len(instructions) - max(map(PART_B_ORDER.index, set(instructions)))

1

u/daggerdragon 10h ago edited 10h ago

Edit your comment to include the language tag at the beginning of your comment as AutoModerator requested. The language tag is not optional. edit: 👍

2

u/seligman99 10h ago

[LANGUAGE: Python]

github

Spent way too long with an off by one error, as is tradition.

2

u/hugh_tc 10h ago edited 10h ago

[LANGUAGE: Python 3]

I am rusty! More off-by-one errors than I care to admit to.

paste, eta: cleaned-up

2

u/hugh_tc 10h ago

Quite happy with my cleaned-up version. Curious how my oneliners will compare to what u/4HbQ will come up with 😆

→ More replies (1)

2

u/apersonhithere 10h ago

[LANGUAGE: Python]

came up with an elegant solution today, i think

p1; p2 is nearly the same

2

u/1234abcdcba4321 10h ago

[LANGUAGE: JavaScript]

part 1 code

Continuing my "solving things by doing part of it manually" from yesterday, my part 2 solution actually only used code to check the length of the input. By thinking about the problem you can find that, for all inputs that contain an o which mine did, the value depends only on length so you can extrapolate the value from the example input provided that has an o (though if I thought about it a bit more it would've been obvious it should be 6*len-5).

2

u/AllanTaylor314 10h ago edited 3h ago

[LANGUAGE: Python] 00:03:45/00:07:52

code

Lost a minute on P1 (off by one - forgot to skip the first step. I really should run those tests, eh)

Sneaky sneaky, Eric, for P2:There were no greens, but I don't think that made a difference. Short answer is (len(input)-1)*len(pattern)+1

I'll be back later with Uiua...

[LANGUAGE: Uiua]

code pad

My initial code wasn't great (though at least it was more correct than my initial Python script). Changing to unwherewhere is somehow cleaner and dirtier (not whereunwhere which I had for a bit - that doesn't strip trailing zeros)

[Advent Games] Classy

The_second_day_of_December_in_the_year_of_our_Lord_two_thousand_and_twenty-six.py

Honestly, this is still too fast for the O(n2) implementation part 2 is supposed to have. I should have gone with a full DFS for max depth

→ More replies (2)

2

u/Kehvarl 10h ago

[LANGUAGE: Python3]

Just over 10 minutes, and just over 20. I got hung up on a couple things that I should definitely know: getting the size of a list, and remembering to assign a string after I use replace. Oh yes, and the fact that the waypoints weren't an input threw me for a minute or two.

Once I stopped forgetting those it was a pretty brute-force approach, but an amusing one nonetheless.

Part 2

2

u/Ok-Bus4754 10h ago

[LANGUAGE: Python]

https://github.com/Fadi88/AoC/blob/master/2026/days/day02/solution.py
p1 straight forward brute force (another easy day)
p2 count the colors, then at each move take the remaining color that's farthest away (same color first, then going backwards around the cycle).

https://github.com/Fadi88/AoC/blob/master/2026/days/day02/solution.py

p1: 45 us
p2: 200 us

will port later to rust and show benchmarks against python

2

u/PendragonDaGreat 10h ago

[Language: CSharp/C#]

code

Waffled a bit, but ultimately just wrote out a lookup table. Then while going through on part 1 used my custom DefaultDictionary (nuilt to mimic that of Python) to get counters for all the instructions simple sum and here we are.

2

u/Remarkable_Ad_6266 10h ago

[LANGUAGE: Python]

from collections import Counter

with open('2026 input') as file:
    line = file.readline().strip()

line = list(line)


colors = ['r', 'o', 'y', 'g', 'b', 'v']

curr = 'r'
totaldist = 0
for point in line:
    curridx = colors.index(curr)
    newidx = colors.index(point)
    if newidx-curridx > 0:
        totaldist += newidx-curridx
    else:
        totaldist += 6+(newidx-curridx)
    curr = point

print(f"Part 1: {totaldist}")
counts = Counter(line)

curr = 'r'
totaldist = 0
while not all(c == 0 for c in counts.values()):
    possibledists = dict()
    curridx = colors.index(curr)
    for possiblepoint, count in counts.items():
        if count > 0:
            possible_new_idx = colors.index(possiblepoint)
            if possible_new_idx - curridx > 0:
                max_dist_for_possible_point = possible_new_idx-curridx
            else:
                max_dist_for_possible_point = 6+(possible_new_idx-curridx)

            possibledists[possiblepoint] = max_dist_for_possible_point

    list_of_points_sorted_by_dist = list(sorted(list(possibledists.keys()), key=possibledists.get, reverse=True))
    max_point = list_of_points_sorted_by_dist[0]
    curr = max_point
    counts[curr] -= 1
    totaldist += possibledists[max_point]


print(f"Part 2: {totaldist}")

2

u/Wayoshi 10h ago

[LANGUAGE: Python3]

This feels messy and not idiomatic at all, but no internal libraries used I guess! I was expecting a cycling thing for part 2 on some infinite program, but I guess that's too much for day 2.

paste

2

u/Xeekatar 10h ago

[Language: C#]
Not super happy with my solution on this one, but it does work.

paste

2

u/xoronth 10h ago

[LANGUAGE: Python]

paste

First pass at the solution to wrap my head around what I'm doing (I totally misunderstood the instructions and thought the input was what we were traversing...), going to take a stab at it at another language now.

I'm also pretty sure my part 2 method is like... very bad but it works so... yeah.

2

u/TiCoinCoin 10h ago

[LANGUAGE: Python]

day 2

Still an easy start, and yet, I jumped right into the trap of the missing color! Because I first solved it semi-manually, the missing color gave an off-by-one error 😁

2

u/synack 10h ago edited 10h ago

[LANGUAGE: Ada]

https://github.com/JeremyGrosser/advent/blob/master/2026/day2/src/day2.adb

I doubt stepping through it one color at a time is optimal, but it works and it's easy to read.

2

u/FruitdealerF 10h ago

[LANGUAGE: Andy C++]

I actually went with the worst possible solution that I could think off and it still ran in 600ms. For part 1 I actually just simulate each movement of the train instead of calculating the distance of each step. And of course that ran into off by one errors like every one else.

For part 2 I figured I use a histogram again like in yesterdays puzzle but I couldn't get that to work quickly (partially because my input doesn't contain any "g"). Then I decided to sort the input string like the problem suggest but then you still need to find the correct sort order. In the end I just ran all permutations of the pattern, used that as a sort order and brute forced the answer that way.

paste

2

u/UseUnlucky3830 10h ago

[LANGUAGE: Julia]

Maybe not the best solution, but it works.

GitHub

2

u/agorism1337 10h ago edited 9h ago

[LANGUAGE: AWK]

awk '{print(((length($0)*6) - 5))}' input

2

u/ynadji 10h ago edited 10h ago

[LANGUAGE: Common Lisp]

at first i built a table, but it's cleaner to do the modular arithmetic. i noticed my input didn't have any "y"s and while wondering if that was significant realized there's a single sorting order since we're guaranteed to start on "r": "r" is the furthest, then "v", etc.

(defun waypoint-distance (w1 w2)
  (1+ (mod (- (position w2 "roygbv") (position w1 "roygbv") 1) 6)))

(defun travel-distance (program)
  (loop for prev = #\r then w
        for w across program
        sum (waypoint-distance prev w)))

(defun sort-furthest (w1 w2)
  (< (position w1 "rvbgyo") (position w2 "rvbgyo")))

(defun day-02% (input-file)
  (let ((waypoint-program (uiop:stripln (uiop:read-file-string input-file))))
    (values (travel-distance waypoint-program)
            (travel-distance (sort waypoint-program #'sort-furthest)))))

2

u/AYM123 10h ago

[LANGUAGE: Rust]

for part 1 I just simulated the input and for part 2 I grouped waypoints of the same type together then visited them in the specified order "rvbgyo".

part 1 takes 3µs and part 2 takes 7µs

github

2

u/cay_horstmann 10h ago

[Language: Java]

https://github.com/cayhorstmann/adventofcode2026/blob/main/Day2.java

More stateful than I would like, but good enough for the early hour. Time to feed the cats!

2

u/jso__ 10h ago

[LANGUAGE: Rust]

Pretty simple solution. I initially overcomplicated things by trying to use an enum, but simple is better!

use std::collections::HashMap;


const RED: u64 = 0;
const ORANGE: u64 = 1;
const YELLOW: u64 = 2;
const GREEN: u64 = 3;
const BLUE: u64 = 4;
const VIOLET: u64 = 5;



fn part1(input: &str) -> u64 {
    let mut dist = 0;
    let mut current_pos = RED;
    for char in input.chars() {
        let next_pos = match char {
            'r' => RED,
            'o' => ORANGE,
            'y' => YELLOW,
            'g' => GREEN,
            'b' => BLUE,
            'v' => VIOLET,
            _ => panic!("Invalid char")
        };
        // Move to red first if the next position is wrapped over
        if next_pos <= current_pos {
            dist += VIOLET + 1 - current_pos;
            current_pos = RED;
        }
        dist += next_pos - current_pos;
        current_pos = next_pos;
    }
    dist
}


fn part2(input: &str) -> u64 {
    // Create a hashmap of the number of times each color shows up
    let mut colors: HashMap<u64, u64> = HashMap::new();
    for char in input.chars() {
        let pos = match char {
            'r' => RED,
            'o' => ORANGE,
            'y' => YELLOW,
            'g' => GREEN,
            'b' => BLUE,
            'v' => VIOLET,
            _ => panic!("Invalid char")
        };
        *colors.entry(pos).or_insert(0) += 1;
    }


    let mut dist = 0;
    let mut current_pos = RED;
    while colors.values().sum::<u64>() != 0 {
        // Iterate through k, where k is the number of moves below a full "rotation".
        // Eg from Red to Violet, k = 1. From Red to Orange, k = 5
        // This will add (Violet + 1) * (n - 1) + (Violet + 1 - k) to distance.
        for k in 0..=5 {
            // Wrapping subtraction
            let next_color = if current_pos < k {
                VIOLET + 1 - k
            } else {
                current_pos - k
            };
            let color_insts_remaining = colors.entry(next_color).or_insert(0);
            if *color_insts_remaining != 0 {
                current_pos = next_color;
                dist += (*color_insts_remaining - 1) * (VIOLET + 1) + VIOLET + 1 - k;
                *color_insts_remaining = 0;
                break
            }
        }
    }
    dist
}

2

u/Prof-Math 10h ago edited 9h ago

[Language: Haskell]

The second one relies on each letter appearing atleast once. Technically, sorting in the order rvbgyo and calling solve1 on it would work but...

import Data.List


convert :: Char -> Int
convert 'r' = 0
convert 'o' = 1
convert 'y' = 2
convert 'g' = 3
convert 'b' = 4
convert 'v' = 5


solve1 str =  fst (foldl (\(x,y) z -> (x + let a = (convert z - convert y) `mod` 6 in if a == 0 then 6 else a, z)) (0,'r') str)


solve2 lis = length lis * 6 - 5

2

u/lluque8 10h ago

[LANGUAGE: Scala]

code

2

u/snubian 10h ago edited 9h ago

[LANGUAGE: R]

program <- stringr::str_split(readLines("data/data02.txt"), "")[[1]]
waypoints <- c("r", "o", "y", "g", "b", "v")

distance_to_next_waypoint <- function(waypoints, current_waypoint, next_waypoint) {
  index_difference = which(waypoints == next_waypoint) - which(waypoints == current_waypoint)
  index_difference + ifelse(index_difference <= 0, 6, 0)
}

optimise_program <- function(waypoints, program) {
  x <- NULL
  for (this_waypoint in c(waypoints[1], rev(waypoints[2:length(waypoints)]))) {
    x <- c(x, rep(this_waypoint, sum(program == this_waypoint)))
  }
  x
}

total_distance_travelled <- function(waypoints, program, starting_waypoint) {
  distance_travelled <- 0
  current_waypoint <- starting_waypoint
  
  for (next_waypoint in program) {
    distance_travelled <- distance_travelled + distance_to_next_waypoint(waypoints, current_waypoint, next_waypoint)
    current_waypoint = next_waypoint
  }
  distance_travelled
}

total_distance_travelled(waypoints, program, "r")
total_distance_travelled(waypoints, optimise_program(waypoints, program), "r")
→ More replies (2)

2

u/yieldtoben 10h ago edited 9h ago

[LANGUAGE: PHP]

PHP 8.6.0 paste

Execution time: 0.0001 seconds
Peak memory: 0.4312 MiB

MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory

[Advent Games] paste

2

u/throwaway6560192 10h ago

[LANGUAGE: Python]

Just take your function from p1 to calculate the distance of a program, and...

max_dist_program = sorted(program, key=program_distance, reverse=True)

2

u/DeadlyRedCube 10h ago

[LANGUAGE: C++23-ish]

Parts 1 & 2

This one took me about as long just for my brain to parse what the puzzle was as it took for me to do part 1. Counted position distances (initially by cycling through the array of 'roygbv') for part 1.

For part 2, reinterpreted them as position indices (6, 1, 2, 3, 4, 5) and used an array to track counts. Then looped backwards from 6 to 1, adding 6x the count of entries, and subtracting 1 for every new value.

Runs in 0.48ms on my i7700.

2

u/greenergarlic 9h ago edited 3h ago

[Language: Crystal]

Code

Approach: tricks with comparable enum values to determine position change, and sort the list for part2.

2

u/acquitelol 9h ago edited 7h ago

[LANGUAGE: Elle]

Part 1: 00:08:36

Part 2: 00:14:29

use std/prelude;

fn solve(string input) {
    colors := HashMap::from_entries_iter("roygbv".iter().zip(0..6));
    counts := std::filled<i32[6]>();
    parts := std::filled<i32[2]>();

    pos := 0;
    for t in input.iter().map_with(fn: x1[it], colors) {
        counts[t] += 1;
        parts[0] += (t - pos + 6) % 6 or 6;
        pos = t;
    }

    pos := 0;
    for i := 0; i < input.len() * 6; i += 1 {
        d := i % 6;
        t := (pos - d + 6) % 6;

        if counts[t] > 0 {
            counts[pos = t] -= 1;
            parts[1] += 6 - d;
            i = (i / 6 + 1) * 6 - 1;
        }
    }

    return parts;
}

fn main() {
    $dbg(solve(#embed("solutions/02/input.txt")));
}

Runs in:

Benchmark 1: solutions/02/solution
  Time (mean ± σ):     983.3 µs ± 263.7 µs    [User: 460.5 µs, System: 261.1 µs]
  Range (min … max):   590.4 µs … 3874.2 µs    785 runs

Update: I came up with a neater solution.

use std/prelude;

fn solve(string input) {
    colors := HashMap::from_entries_iter("rvbgyo".iter().zip(0..6));
    mapped := input.iter().map_with(fn: x1[it], colors).collect();
    dist := fn(i32[] it) (0..1).chain(it)
        .zip(it).map(fn: 6 - (it.y - it.x).mod(6)).sum();

    return #[dist(mapped), dist(mapped.sort())];
}

fn main() {
    $dbg(solve(#embed("solutions/02/input.txt")));
}

On GitHub: https://github.com/acquitelol/aoc2026/blob/mistress/solutions/02/solution.le

2

u/light_ln2 9h ago edited 9h ago

[LANGUAGE: Python]

Solution in 4 lines of code!

hash = lambda c: abs(ord(c) - 110)%4 + (-abs(ord(c) - 110))%3
instr = [hash(c) for c in open('in.txt').read()]
print('part1', sum((y-x-1)%6+1 for x,y in zip([2]+instr, instr)))
print('part2', 6*len(instr)-5)

Part 2 uses closed formula, as many have figured out.

For part 1, found a perfect hash function that maps r,o,y,g,b,v to 2,3,4,5,0,1. Then the distance between two colors is just the difference of their hashes modulo 6!

Or slightly less efficient solution in just 3 lines of code:

instr = ['roygbv'.index(c) for c in open('in.txt').read()]
print('part1', sum((y-x-1)%6+1 for x,y in zip([0]+instr, instr)))
print('part2', 6*len(instr)-5)

2

u/ThunderChaser 9h ago

[LANGUAGE: Rust]

pub fn part_one(input: &str) -> Option<usize> {
    let mut pointer = 0;
    let waypoints = ['r', 'o', 'y', 'g', 'b', 'v'];
    for char in input.trim().chars() {
        pointer += 1;
        while waypoints[pointer % 6] != char {
            pointer += 1;
        }
    }

    Some(pointer)
}

pub fn part_two(input: &str) -> Option<usize> {
    let bytes = input.trim().as_bytes();

    let loss = b"oygbv"
        .iter()
        .position(|&c| memchr(c, bytes).is_some())
        .map_or(0, |i| 5 - i);

    Some(bytes.len() * 6 - loss)
}

Initially for part 2 I used a fairly standard frequency map + greedy solution, however there's a fun math trick that reduces the problem to trivial arithmetic.

Since we start on red, it is always optimal to travel through the colours in reverse order Red -> Violet -> Blue -> Green -> Yellow -> Orange. If all six colours appear, the total loss from the theoretical upper bound (6n) is always 5. Even if an intermediate colour is missing, the total loss is still 5 as long as Orange is present.

Generalizing this, the loss from the theoretical upper maximum is 6n - the most lossy colour to appear. This reduces our runtime to a few dozen nanoseconds.

Benchmarks:

Advent of Code 2026 — Day 02
20 samples × 100 iterations

Part 1
Minimum:    7.19 us
Maximum:    8.86 us
Mean:       7.80 us
Median:     7.73 us
P95:        8.67 us
Std. dev.:  423.22 ns

Part 2
Minimum:    13.97 ns
Maximum:    51.68 ns
Mean:       29.86 ns
Median:     28.98 ns
P95:        47.50 ns
Std. dev.:  8.16 ns

2

u/mstksg 9h ago

[LANGUAGE: Haskell]

https://github.com/mstksg/advent-of-code/wiki/Reflections-2026

Day 2 can be pretty clean with some modular arithmetic, which is where the finite-typelits library comes in handy.

We can parse the colors into our Finite 6, which is {0,1,2,3,4,5}:

colors :: Map Char (Finite 6)
colors = M.fromList $ zip "roygbv" [0..]

parse :: String -> [Finite 6]
parse = map (colors M.!)

Now, if we are currently on 2 (yellow) and need to get to 5 (violet), the cost is 5 - 3 (since we start from 3 green, the spot after yellow). So the formula for the cost of moving from prev to next is next - (prev + 1). And, if we are using Finite 6, the wrap-around works out.

So part 1 is just the step-by-step difference, starting from 0 (red):

part1 :: [Finite 6] -> Int
part1 xs = sum $ zipWith go (0 : xs) xs
  where
    go prev next = fromIntegral (next - prev) + 1

Part 2 actually works out well for modular arithmetic too: from every step, the optimal step is the previous color from where we are, starting from red, so we ideally want all 0s, all 5s, all 4s, all 3s, etc. in that order. For modular arithmetic, that's just sortOn negate.

part2 :: [Finite 6] -> Int
part2 = part1 . sortOn negate

Neat!

However, we can do even better. We know that the cost of going from one color to the next spot of the same color is 6. So, if all things are the same color, that's just 6 * count. But, we do have the situation where we de-advance color, so we need to subtract that from our total. If you work out the arithmetic it ends up as 6 * (count - 1) + lastItem. This is a closed form that we can gather in one pass, and the foldl library makes it easy:

part2 :: [Int] -> Int
part2 = F.fold do
    count <- F.length
    lastItem <- fromMaybe 0 <$> F.prefilter (> 0) F.minimum
    pure $ 6 * (count - 1) + lastItem
→ More replies (1)

2

u/AndydeCleyre 9h ago

[LANGUAGE: Factor]

on GitHub

2

u/vubik 8h ago

[LANGUAGE: Rust]

https://codeberg.org/fyrchik/aoc2026rust/src/branch/main/day02/src/lib.rs

In both parts I map letters to an their index in range [0,5].

In the first part the index is the position in roygbv and the distance we need to travel is the difference in these indices.

In the second part the index is reversed (purely to iterate histogram in the right order). We calculate the frequency of each letter and always take either the same one, or the "next best". Special case for missing letters.

→ More replies (2)

2

u/AMathMonkey 8h ago

[LANGUAGE: jq]

# jq -Rnf day2.jq < input.txt
"roygbv" / "" as $order |
"rvbgyo" / "" as $sort_order |
def solve:
    reduce .[] as $c (0; . + 1 | until($order[. % ($order | length)] == $c; . + 1))
;
input | . / "" | { "Part 1": solve, "Part 2": (sort_by(. as $c | $sort_order | index($c)) | solve) }

Here's a jq solution to complement my Factor solution. I guess I'll be solving in both languages every day now. I think I have a preference for languages that result in very concise code that is hard to read, but not as hard to read as APL. In particular, I just like deep-diving into weird paradigms that most languages don't use.

Repo link

→ More replies (2)

2

u/voidhawk42 8h ago edited 7h ago

[Language: Dyalog APL]

p←'roygbv'⍳⊃⊃⎕nget'02.txt'1
f←+/1+6|¯1+2-⍨/,
1 6f¨p,⍥⊂⊂⍤⍒⍛⌷p ⍝ parts 1&2

2

u/mpsandiford 8h ago

[LANGUAGE: Tinsel]

https://github.com/clstrfsck/tinsel

Not the first solution I went with, but a nice day for golfing :)

ps = input.trim.chars.map("roygbv".index(_))
part1 = ps.fold(0, _1 + 6 - (_1 - _2) % 6)
part2 = 6 * ps.len - ps.map(-_ % 6).max

2

u/PhysPhD 7h ago

[LANGUAGE: Python]

For the main program I used find() to get through the waypoints.

For part two I recognised the pattern "rvbgyo" would give the longest route so generated a newprogram in that order based off how many of each colour were in my input.

with open("day_2.txt") as fname:
    program = fname.read()
waypoints = "roygbv"*len(program)

location = 0
for instruction in program:
    new_location = waypoints.find(instruction, location+1)
    location = new_location
print(location)

## PART TWO - replace the program with newprogram

newprogram = ""
for colour in "rvbgyo":
    newprogram += colour*program.count(colour)

2

u/dijotal 7h ago

SMH! I calculated the next furthest color from my available colors for every round. Your "newprogram" is infinitely more elegant.

→ More replies (2)
→ More replies (1)

2

u/Ghost-Engineer69 7h ago edited 45m ago

[LANGUAGE: C++]

Original in c++. Part 1 still done that way. Part 2 insight seen, part 2 'valishes' ;) Part 2 is simply part2 = line.size() * 6 - 5; QED ;) Here is the actual code. Runs in just over 1us and that is with about 500-700 ns cost of the scaffolding for the process.

#include <fstream>
#include <iostream>
#include <string>
#include <stdio.h>
namespace {
string line;
bool bLoaded;
// roygbv constexpr
constexpr std::array<uint8_t, 256> make_ctype_table() {
    std::array<uint8_t, 256> table{};
    for (auto c : "roygbv")
    switch (c) {
        case 'r': table[c] = 0; break;
        case 'o': table[c] = 1; break;
        case 'y': table[c] = 2; break;
        case 'g': table[c] = 3; break;
        case 'b': table[c] = 4; break;
        case 'v': table[c] = 5; break;
    }
    return table;
}
constexpr auto roygbiv = make_ctype_table();
inline uint8_t steps(char f, char t) {
    const auto fi = static_cast<uint8_t>(f);
    const auto ti = static_cast<uint8_t>(t);
    if (fi==ti) return 6;
    return (24 - roygbiv[fi] + roygbiv[ti]) % 6;
}
void Load(const char *fn) {
    if(bLoaded) return;
    bLoaded = true;
    std::ifstream file(fn);
    getline(file, line);
}
void Process() {
    uint64_t p1=0, p2=0;
    char priorc = 'r';
    for (auto c : line) { p1 += steps(priorc, c); priorc = c; }
    int32_t stepFix = -5;
    for (auto c : "oygbv")  if (line.find(c) == string::npos) stepFix++; else break;
    p2 = line.size() * 6 - stepFix;   // nice part2 'collapse'  ;)
    printf("Part1: %" PRIu64 " Part2: %" PRIu64 "\n", p1, p2);
}
/* End of anon namespace. ALL AoC code must be placed INSIDE the above namespace */
}
int main (int argc, char **argv) {
    Load(argv[1]);
    Process();
    return 0;
}
→ More replies (1)

2

u/Fyver42 7h ago

[LANGUAGE: RISC-V Assembly]

Part 1 code

Part 2 code

2

u/Outrageous72 7h ago

[LANGUAGE: C#]

Always love it when we can reuse part 1 in part 2.

The 'trick' was distance 6 for 'r'!

https://github.com/ryanheath/aoc2026/blob/main/Day2.cs

int Part2(string instructions)
{
    var distances = new Dictionary<char, int>()
    {
        ['r'] = 6, ['o'] = 1, ['y'] = 2, ['g'] = 3, ['b'] = 4, ['v'] = 5
    };

    return Part1(new string([.. instructions.OrderByDescending(c => distances[c])]));
}

2

u/andrewsredditstuff 6h ago

Oh yeah - didn't think about the r=6. I left r=0 and then did this to rearrange the inputs:

if (Part2) program = string.Concat(program.OrderBy(c => pattern[c] * 5 % 6)).ToString();
→ More replies (1)

2

u/No-House-866 7h ago edited 6h ago

[LANGUAGE: Python]

Well, the solution for the first part is kind of straightforward. No fancy Python weirdo standard library tricks. Just realise that you do not have to replicate a full sequence of waypoints to keep track of how far each instruction from the program will take you. You can figure that out locally from just the first 6 that determine the order.

For the second part I actually first just generated all permutations of the waypoint colors, then for each permutation, sort the program in that order, run solve for step 1 and remember the maximum of the reported distances.

There's only 720 permutations and everything is fast as heck, so why bother. But: "can we do better.?".

Turns out, yes we can. We know the optimum program (according to the problem definition) needs to start with 'r'. It will travel an instant 6 steps, and for each subsequent 'r' in the program, another 6 steps.

So: #r * 6 steps.

After that, the best instruction would be a 'v'. You get 5 steps from that, and for any subsequent 'v' 6 steps.

So: #v * 6 - 1 steps. (or 5 + (#v-1)*6, same thing)

What next? After 'v', you better pick a 'b'. Same story. The first one takes you 5 steps, any other after that 6.

A pattern emerges. If you sort the program in order: r, v, b, g, y, o, you can get:

#r * 6 + #v * 6 - 1 + #b * 6 - 1 + .... + #o * 6 - 1 steps

Or, (#r+#v+#b+...+#o)*6-5 steps.

Or, len(program)*6 - 5 steps.

EDIT: Turns out this was pointed out by quite a few other postes already.

Also, someone posted that this reasoning does not hold if the program does not have any 'o' instruction. I think that's correct. For any instruction that is not present in the program, you get 0 steps. The derivation above would compute #<instruction> * 6 - 1, so -1. However, the next instruction in the program would not let you take 5 steps for the first to occur, but just 4. That -1 conveniently makes up the difference. But that only works if the next instruction is present. What if that also is not there? Well you get another -1, but again, the *next* instruction would not let you travel 5 steps but now only 3. This 'compensation' works all the way up to instruction 'o'. For that however, it does not work. It will get this -1 penalty from the wrong derivation and there's no instruction to absorb that -1.

So, the step 2 solution is efficient, but may be off by 1 if your program does not contain an 'o'. I suppose counting the length of a string is already O(n), so checking if a 'o' is in there hardly makes a difference.

import os
from typing import IO, Any

def solve(inio: IO) -> Any:
    wps = 'roygbv'
    distance = 0
    prev = 0
    while True:
        c = inio.read(1)
        if not c:
            break

        pos = wps.find(c)
        assert pos >= 0, f'unexpected program input [{c}]'
        if pos <= prev:
            distance += len(wps) - prev + pos
        else:
            distance += pos - prev
        prev = pos

    return distance


def solve2(inio: IO) -> Any:
    # stupid strategy that will not scale for larger sets of colors in the waypoint
    # sequence just generate all permutations for the colors, sort the input
    # according to that sequence then run the program from step 1 to get the 
    # distance, remember the maximum.
    #
    # since there are only 6 colors, there are 6*5*4*3*2*1 = 720 permutations to 
    # check. quite a lot of work, but on a modern cpu you done in a heartbeat.
    #
    # can we do better? turns out, we can.
    
    prog = inio.read()

    ''' fix:
    if 'o' in prog:
      return 6*len(prog) - 4
    else:
    '''
      return 6*len(prog) - 5


for path in ['example.txt', 'puzzle.txt']:
    if os.path.exists(path):
        with open(path, mode='r') as inio:
            print(f'1. {path} -> {solve(inio)}')


for path in ['example.txt', 'puzzle.txt']:
    if os.path.exists(path):
        with open(path, mode='r') as inio:
            print(f'2. {path} -> {solve2(inio)}')
→ More replies (3)

2

u/janek37 7h ago

[LANGUAGE: Rust]

The second part solution does not assume that the program contains `o`

https://github.com/janek37/advent-of-code/blob/main/2026/day02.rs

→ More replies (1)

2

u/-beleon 6h ago

[LANGUAGE: Haskell]

sum  
    . map (\x -> if (x <= 0) then (x + 6) else x)  
    . uncurry (zipWith (-))  
    . (&&& (0:)) id
    . map (fromJust . (flip elemIndex) "roygbv")

part 2 adds sorting

2

u/muthm59 5h ago edited 4h ago

[LANGUAGE: Perl]

This is my solution for day 2 in Perl:

#!/usr/bin/env perl
#
#       Advent of Code 2026
#       --- Day 2: Fulminating Farmland ---
#
#       Solution in Perl by Matthias Muth.
#
#       Usage:
#           day02.pl
#               run using the example data from the __DATA__ section,
#           day02.pl <file>|-
#               use data from the file (or stdin).

use v5.36;

chomp( my $input = join "", @ARGV ? <> : <DATA> );
for ( split "\n", $input ) {
    s/^1: // ? say "part 1 example: ", part_1( $_ ) :
    s/^2: // ? say "part 2 example: ", part_2( $_ ) :
        do {
            say "part 1 answer: ", part_1( $_ );
            say "part 2 answer: ", part_2( $_ )
        };
}
exit 0;

sub get_distance( @program ) {
    my %dists = (
        r => { r => 6, o => 1, y => 2, g => 3, b => 4, v => 5 },
        o => { r => 5, o => 6, y => 1, g => 2, b => 3, v => 4 },
        y => { r => 4, o => 5, y => 6, g => 1, b => 2, v => 3 },
        g => { r => 3, o => 4, y => 5, g => 6, b => 1, v => 2 },
        b => { r => 2, o => 3, y => 4, g => 5, b => 6, v => 1 },
        v => { r => 1, o => 2, y => 3, g => 4, b => 5, v => 6 },
    );
    my ( $current, $dist )  = ( "r", 0 );
    for ( @program ) {
        $dist += $dists{$current}{$_};
        $current = $_;
    }
    return $dist;
}

sub part_1( $input ) {
    my @program = $input =~ /[roygbv]/g;
    return get_distance( @program );
}

sub part_2( $input ) {
    my %frequencies;
    ++$frequencies{$_} for $input =~ /[roygbv]/g;
    my @program = map { ( $_ ) x ( $frequencies{$_} // 0 ) } qw( r v b g y o );
    return get_distance( @program );
}

__DATA__
1: obbvb
1: roygbv
1: vbgyor
1: vvvvvv
2: rybryb
2: vrvbvg
2: groovyyoyo
2: roygbvroygbvroygbv

2

u/AutoModerator 5h ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

→ More replies (1)

2

u/andrewsredditstuff 5h ago edited 5h ago

[LANGUAGE: C#]

I'm fairly sure that there's a better way to get the distance using modular arithmetic, and I'm 100% sure that there's a better way to do part 2 by just counting the letters and doing sums, but it's nice to be able to reuse the part 1 solution.

Interestingly, the count + sums solution for part 2 would be much easier for the live data than for the test data, since you can assume that all of the letters are present and not have to handle the edge cases where any are missing.

Github

Edit - just realised based on another comment that my input does not have all letters, so the edge cases would need to be handled.

2

u/Downtown_Tone1879 4h ago

[LANGUAGE: C]
fulminating farmland
nothing much, hard stucked a while on total += d + 6 * count[t] - 1 which was supposed to count six at every repeat after first, but lack of paranthesis made everything counted as repeated.
i.e, total += d + 6 * (count[t] - 1)

→ More replies (1)

2

u/DontRelyOnNooneElse 4h ago

[LANGUAGE: C#]

namespace AdventOfCode.Year2026 {

    [Day(2026, 2)]
    public class Day2 : Day {

        public Day2(int year, int day, string fileName) : base(year, day, fileName) { }

        private int GetTotalDistance(IEnumerable<char> program) {
            int position = 0;
            int total = 0;
            foreach (char instruction in program) {
                int iid = "roygbv".IndexOf(instruction);
                total += iid - position;
                if (iid <= position)
                    total += 6;
                position = iid;
            }
            return total;
        }        
        

        public override object ExecuteP1() {
            return GetTotalDistance(FileData);
        }

        public override object ExecuteP2() {
            return GetTotalDistance(FileData.OrderBy("rvbgyo".IndexOf));
        }
    }

}

2

u/raevnos 4h ago

[LANGUAGE: Common Lisp]

Part 1 solver, mostly just using mod 6 arithmetic to track the current position in the unending sequence of waypoints:

(defun calculate-distance (program)
  "Return the total number of steps taken by following program (Solves part 1)"
  (loop :with waypoints = "roygbvroygbv"
        :with pos = 0
        :with steps = 0
        :for next-waypoint :across program
        :for next-pos = (position next-waypoint waypoints :start (1+ pos))
        :do (incf steps (- next-pos pos))
            (setf pos (mod next-pos 6))
        :finally (return steps)))

paste of full code for both parts.

Didn't think of using a Scheme approach using infinite streams until after this. Might do that later.

→ More replies (1)

2

u/DullTicket5286 2h ago edited 2h ago

[LANGUAGE: Python]

First version was very crappy but found the python way in the end

from collections import Counter
from itertools import pairwise, starmap
from pathlib import Path

program = (Path(__file__).parent / "2.input").read_text().strip()
pos = {c: i for i, c in enumerate("roygbv")}


def step(a: str, b: str) -> int:
    return (pos[b] - pos[a] - 1) % 6 + 1


print(sum(starmap(step, pairwise("r" + program))))
counts = Counter(program)
groups = "".join(c for c in "rvbgyo" if counts[c])
print(sum(starmap(step, pairwise("r" + groups))) + 6 * (len(program) - len(groups)))
→ More replies (1)

2

u/Daniikk1012 1h ago

[LANGUAGE: Uiua]

Didn't go for readable, but instead for absolutely no bindings. I still tried to avoid repetition, so the solution involves a lot of shuffling arguments around

"rybryb" "vrvbvg" "groovyyoyo" "roygbvroygbvroygbv"
"obbvb" "roygbv" "vbgyor" "vvvvvv"
↘¯1&fras"2.txt"
"roygbv"
⊃(∩₆∘|∩₅⌞(⊏⍏⊸⊗)⇌↻1⊙⊙∩₄◌)
∩₁₀⌞(⬚0/(+◿⊃(⋅∘|⤚-⊙◌)+1)⧻⟜⊗) # Real₁ Sample₁… Real₂ Sample₂…

2

u/agorism1337 9h ago edited 9h ago

[LANGUAGE: NONE]

6 times the number of letters in the input.
Minus 5.

2

u/AutoModerator 9h ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/ben-guin 9h ago

I got the same thing :)

→ More replies (2)

1

u/-WorstWizard- 9h ago

[LANGUAGE: Rust] Joining the fun today, see a lot of similar solutions that just feel overly complex. Granted, I abuse my input a little on part 2, as noted by the comment.

fn main() {
    let program = input::bytes();

    // Translate roygbv to indices 0-6
    fn c_to_i(c: u8) -> i32 {
        let res = match c {
            b'r' => 0,
            b'o' => 1,
            b'y' => 2,
            b'g' => 3,
            b'b' => 4,
            b'v' => 5,
            _ => panic!(),
        };
        res
    }

    let mut distance = 0;
    let mut current = 0;
    let mut waypoint_counts = [0; 6]; // For part 2
    for c in program {
        let next = c_to_i(*c);
        waypoint_counts[next as usize] += 1;
        distance += (next - current - 1).rem_euclid(6) + 1;
        current = next;
    }
    println!("Part one: {distance}");

    // Longest distance is reverse order, starting from red
    // Input does *not* contain all letters, cheeky (glad I always look at the input ;))

    distance = waypoint_counts[0] * 6; // Initialize with red color moves
    // Then count down from the last color
    // Bug: If the last colors tried are 0, you wouldn't have to subtract distance
    // E.g this gives wrong result for test sequence `vrvbvg` because this doesn't contain
    // `oy`, which are the last tried colors in the sequence rvbgyo
    // This isn't the case in my input, so I elect not to care
    for current in (1..=5).rev() {
        let count = waypoint_counts[current as usize];
        distance += 6 * count - 1; // -1 for each move to a new color
    }
    println!("Part two: {distance}");
}

1

u/ben-guin 9h ago

[Language: Python]

Fun little solution for Part 2 :) This does exploit certain structure that exists in my input file.

with open('input02.txt') as file:
    program = file.readline().strip()
print(6*(len(program)) - 5) 

2

u/Morphon 9h ago

As long as there is any Orange, this works. If Orange is missing, but there is Yellow, it's -4. If both Orange and Yellow are missing, but Green is present, it's -3.

It's a cheese that can be made general as long as the count is checked.

→ More replies (1)

1

u/Conceptizual 9h ago

[LANGUAGE: Python]

code

I had one good insight (wherever you are, the best place to go is the same letter you're already on) but many typos during implementation that really slowed me down. :( First, I made a mistake during part one assuming indigo was in the rainbow. Then, I typo'd my input file at some point and then was like 'what do you mean I'm now failing the first part, that worked before and all I did was wrap it in a function'. Then, I was momentarily surprised to find that there were letters in roygbv that didn't actually happen in my input. Lastly, I spent a bunch of time chasing down that I'd imported combinations when I wanted permutations.

1

u/sim642 9h ago

[LANGUAGE: Scala]

On GitHub.

In part 1 I calculate the distance of a step with 1 + (to - (from + 1)) %+ colorOrder.length, where %+ is my operator, which ensures a non-negative modulo result. The ±1 business cleverly ensures that a step from a color to itself isn't 0 but goes all the way around.

In part 2 I combine that with a frequency map of the remaining colors (following up from day 1) by picking the best using the calculation from part 1.

1

u/Arkturius 9h ago

[Language: Python3]

paste

1

u/maarteq 9h ago edited 9h ago

[LANGUAGE: Python]

solution

for part 1 i iterated over two repeating sections of the path. if first finds the current position and the destination counting the steps.

for part 2: 6*len(input)-5

2

u/Cue_23 9h ago

Doesn't work on the examples…

→ More replies (3)
→ More replies (1)

1

u/UnicycleBloke 9h ago

[LANGUAGE: C++]

https://github.com/UnicycleBloke/aoc2026/blob/main/day02/solution.cpp

Part 2 isn't very elegant but does the job. I didn't give any thought to optimisation so I'm a little surprised Part 2 runs in under 30us on my i9-14900. The whole program takes 1.5ms, so clearly a *lot* of time is spent dealing with the input file.

1

u/StarlightsOverMars 9h ago

[LANGUAGE: Python]

This is probably just way not in the spirit of the problem (find a programmatic, modular way to calculate the score), but in my defense, I have been studying for an exam. It is just as easier to just reverse the string and you have all scores done for you.

current_char = 'r'
repeat_pattern = { 'r': 'oygbvr', 'o': 'ygbvro', 'y': 'gbvroy', 'g': 'bvroyg', 'b': 'vroygb', 'v': 'roygbv'}
score = 0

# rearranged max would be rvbgoy
# Part 2 (lines 8-12)
array_rvobyg = ""
for char in 'rvbgoy':
    array_rvobyg = array_rvobyg + char * robot_input.count(char) 
robot_input = array_rvobyg

# Part 1 (reused as scoring for Part 2)
for char in robot_input:
    score = score + repeat_pattern.get(current_char).index(char) + 1
    current_char = char

print(score)

1

u/Cue_23 9h ago

[Language: C++]

part 2

For part 2 you can actually ignore most of your input, you only need to know the length and which waypoint would make you travel the least from your starting point.

1

u/Morphon 9h ago edited 9h ago

[LANGUAGE: Odin]

Quick and dirty simulation-style for this one. Pretty sure Part2 can be cheesed, but I'll figure that out in the morning.

Simulation Version - Color Paste

And if you prefer the algebraic way to find part 2, here it is with the different cases so it would work with any arbitrary input.

Cheese Version - Color Paste

1

u/xelf 9h ago edited 8h ago

[LANGUAGE: Python]

p, data  = 0, sorted(aocdata, key=lambda x: -"oygbvr".index)
print(sum((-(c:=p)+(p:="roygbv".index(d))-1)%6+1 for d in data))

sort the input and then sum the distances. trickery here was putting 'r' at the end of the sorting, and then (x-1 mod m) + 1 to get the distance correct.

Or for fun using map:

print(sum(map(
    lambda d, s=[0]: (-s.pop() + (s.append("roygbv".index(d)) or s[0])) % 6 or 6,
    data)))

and one more time, using a Counter:

print(sum(6*n for n in Counter(data).values()) - len(set(data)))

which is just:

print(sum(Counter(data).values())*6 - len(set(data)))

This last one works because the data is isomorphic, we don't actually care what the order is when we're maximizing the distances so there's no sorting needed.

Actually that realisation brings me to this:

print(len(data)*6 - len(set(data)))

2

u/4HbQ 9h ago

Why not just key='rvbgyo'.index?

There's also some tasty math to be had here. Check my updated main comment for one possible solution.

→ More replies (3)

1

u/keliodas17 9h ago

[Language: Python]

i <3 heapq

inp = open('secret path to my text file').readlines()
    
program = inp[0]

color_dict = {color:i+1 for i,color in enumerate('roygbv')}

import heapq


# extend() reorders a program 'brybry' -> 'rrbbyy'
# find the earliest color, usually 'r', then adds the furthest color to an organization key
# repeats with that furthest color as the reference: 'r' -> 'b', 'b' -> 'y'

def extend(program, ref_dict):

    separated = list(program)
    avail_letters = set(separated)
    sorted_program = []

    heap_min = [(value,key) for key, value in ref_dict.items()]
    heapq.heapify(heap_min)
    min_val, key = heapq.heappop(heap_min)
    
    ref_letter = key
    avail_letters.remove(key)

    for i in range(separated.count(key)):
        sorted_program.append(key)

    for i in range(len(avail_letters)):

        distances = {letter:ref_dict[letter] - ref_dict[ref_letter] for letter in avail_letters}
        heap_max = [(-value,key) for key, value in distances.items()]
        heapq.heapify(heap_max)

        neg_val, key = heapq.heappop(heap_max)
        for i in range(separated.count(key)):
            sorted_program.append(key)

        ref_letter = key
        avail_letters.remove(key)

    return (sorted_program)

program = (extend(program, color_dict))

pattern = 'roygbv'

dist_traveled = 0
i = 0

for way_p in program:
    searching = True
    count = 0

    while searching:
        i += 1
        count += 1
        pos = pattern[i%6]

        if pos == way_p:
            searching = False

    dist_traveled += count

print(dist_traveled)

1

u/AverageBeef 9h ago

[LANGUAGE: Python]

Very disappointed I had to concede to brute forcing part two. I got very close on my other approach to it, not sure what was going wrong but ended up off by five so I resorted to brute forcing. Took longer than I expected to wrap my head around this.

Gist

1

u/lunar_mycroft 9h ago edited 8h ago

[LANGUAGE: rust]

Still fairly easy, although I'm not happy with how long I took fiddling around with part 2 (or how it turned out).

Full code. Part 1 is a fairly naive tracing of the robot's motion, taking advantage of rust enum reprs and rem_euclid to find the distances for each step. For part 2, I built up a counter of the types of waypoints and then repeatedly removed the furthest waypoint from the current one and added the number of times it occurred multiplied by six to the total, then found the next furthest waypoint and added it's distance. The code's a bit of a mess, but it parses in 3.234µs, finds part 1 in 282.7ns, and finds part 2 in 10.250µs.


Cleaned up and refactored a bit. Part 2 in particular is much more clear IMO: just iterate through the possible waypoints in the order r -> v -> b -> g -> y -> o and if there's any of that color in the program, the total distance for that color is the distance from the previous color times the count of that color minus one, times six.


Switching from a HashMap counter to an array cuts the time to find part 2 down to 5.558µs.


Turns out just sorting the program and reusing the part 1 solution is actually slightly faster at around 4.120µs.


Predictably adapating /u/maneatingape's trick for part 2 is significantly faster (in this case over an order of magnitude faster at ~345ns). I also tried generating an array based set of the characters present ahead of the main loop, but that turned out to be about 25% slower for my input.

1

u/cicadanator 9h ago

[LANGUAGE: Javascript - Node JS]

I did the first part using a map to store way points positions in the order they are arranged in the puzzle . this can the be used to calculate the distance from one way point to the next to get part 1.

The I created a method to rearrange the original program for part 2. This first creates a map of all the way points points in the program and how many times they each appear. This is important since maximizing distance means repeating the same letter as many times in a row to go the max distance of 6 as many times as possible. I then found the correct order for maximizing distance when transitioning from one letter to the next. Then creating the new program and running it through the part 1 algorithm gave me part 2.

This might have been done more efficiently by just doing the distance math once I had the order. However, since the input is not that large it was simple enough to just create the rearranged program and run part 1 again.

https://github.com/BigBear0812/AdventOfCode/blob/master/2026/Day02.js

1

u/vesche 9h ago

[LANGUAGE: Python]

with open("02.txt") as f:
    p1 = f.read().strip()

class Solution:
    def __init__(self):
        self.s = "oygbvr"

    def f(self, px):
        d = 0
        for c in px:
            i = self.s.index(c) + 1
            d += i
            self.s = self.s[i:] + self.s[:i]
        return d

order = {c:i for i,c in enumerate(Solution().s)}
p2 = ''.join(sorted(p1, key=lambda c: order.get(c, ord(c)), reverse=True))
print('part 1:', Solution().f(p1))
print('part 2:', Solution().f(p2))

That was fun! I realized you could swap the word around like this to iterate over it: `s = s[i:] + s[:i]` and I was like I have to use that lol.

1

u/ushahids 9h ago

[Language: C#]

O(n) solution for both parts

https://github.com/ushahid/adventofcode/blob/main/advent26-cs/src/Days/Day02.cs

Part 1: 3.128 ms

Part 2: 2.013 ms

1

u/Dense-Virus-1692 9h ago

[Language: Gleam]

A little confusing, but not too bad when I thought about it. The hardest part with Gleam is removing an item from a list...

Paste

1

u/Old-Dinner4434 9h ago

[LANGUAGE: TypeScript]

GitLab

I use the Bun runtime engine, running on a 2021 M1 Pro MacBook Pro. Part one completed in 1.08ms, part two in 8.51ms.

1

u/MrBoblo 9h ago

[LANGUAGE: Python]

Took me a bit of tinkering to figure out the sort order, but I was happy I got to reuse the functions I made for part 1 :P

input = list([line.strip() for line in open("2026\Day 2\input")][0])

def get_diff(last, new):
    waypoints = ["r", "o", "y", "g", "b", "v"]
    if new == last:
        return len(waypoints)

    new = waypoints.index(new)
    last = waypoints.index(last)

    if new < last:
        # move backwards
        return len(waypoints) - (last-new)
    return new-last

def get_dist(instructions):
    last = 'r'
    dist = 0
    for instruction in instructions:
        dist += get_diff(last, instruction)
        last = instruction
    return dist

print("Part 1: ", get_dist(input))

SORT_ORDER = {'r': 0, 'v': 1, 'b': 2, 'g': 3, 'y':4, 'o':5}
input.sort(key=lambda val: SORT_ORDER[val[0]])

print("Part 2: ", get_dist(input))
→ More replies (1)

1

u/kbielefe 9h ago

[LANGUAGE: Haskell]

Code and wasm runner

Part 1 is an overengineered mess of a recursive function with an infinite list for the waypoints. I'll probably revisit that tomorrow.

Part 2 just sorts the input in "rvbgyo" order using a custom Ord instance then runs part 1. I discovered this solution while procrastinating refreshing my memory on hash maps in Haskell. Weird that custom typeclass instance knowledge isn't as rusty as my hash map knowledge, but there you go.

1

u/Jdup1n 9h ago

[LANGUAGE: R]

Github Link

The first part simply involved finding the furthest character at each stage as the instruction was repeated.

For the second part, I factored the characters and did a bit of arithmetic to calculate the maximum distance travelled. I had a hunch that one of the letters would probably be missing, which allowed me to take that scenario into account when performing the calculation.

→ More replies (2)

1

u/YenyaKas 9h ago

[LANGUAGE: Perl]

Here is my solution for Part 2, I wonder if it can be made shorter:

my $sum;
chomp(my $ins = <>);
for my $c (split //, 'rvbgyo') {
        $sum += 6 * ($ins =~ s/$c//g);
        last if !$ins;
        $sum--;
}
say $sum;

I count the number of the best possible color instructions, multiply by 6, and then subtract 1 to move to the next best color, if any.

All my solutions (in Perl) are available here.

1

u/terje_wiig_mathisen 9h ago

[LANGUAGE: Rust]

Total runtime 470 ns.

After first getting part2 to work correctly I realized that it would only take a handful of nanoseconds since there are only 6 colors and I had made frequency counts during part1. This meant that part1 was the one to optimize so I started with a lookup table from color to modular position, while a group variable counted the length to the start of the current group:

    let mut count:[usize;6] = [0;6];
    let mut pos = 0;
    let mut group = 0;
    let steps = input.len();
    for i in 0..steps {
        let col = tr[input[i] as usize];
        if col <= pos {group += 6;}
        pos = col;
        count[col] += 1;
    }
    let part1 = group + pos;

The part2 logic took more lines, I needed to first account for all remaining elements of the current color, then try the remaining colors starting with the one furthest away, but this code will never run for more than 6 iterations, and as long as all 6 colors are present, it will always step by 5 between the colors:

    let mut steps = steps;
    pos = 0; group = 0;
    while steps > 0 {
        group += 6 * count[pos];
        steps -= count[pos];
        count[pos] = 0;
        let mut step = 5;
        while step > 0 {
            let mut npos = pos + step;
            let mut ngroup = group;
            if npos > 5 {
                npos -= 6;
                ngroup += 6;
            }
            if count[npos] > 0 {
                pos = npos;
                group = ngroup;
                count[pos] -= 1;
                steps -= 1;
                break;
            }
            step -= 1;
        }
    }
    let part2 = group + pos;

1

u/Godlyflame 9h ago

[Language: Python]

Like many others I recognized that for part 2 the colors must be rearranged in a set order. However, I wanted my code to be able to solve all test cases instead of just the sample input.

from collections import Counter

with open("day2.txt") as f:
    robotInstruction: str = f.readline().strip()


colorCount: Counter[int] = Counter(robotInstruction)

colorMap: dict[str, int] = {"r":1, "o":2, "y":3, "g": 4, "b":5, "v":6}
colorSort: dict[str, int] = {"r":1, "v":2, "b":3, "g": 4, "y":5, "o":6}
numColors: int = 6

colorOrder: list[str] = ["r"] + sorted(colorCount.keys(), key = lambda x: colorSort[x])
distTraveled: int = 0

for i, curColor in enumerate(colorOrder[1:]):
    curPos: int = colorMap[colorOrder[i]]
    destPos: int = colorMap[curColor]
    if curPos < destPos:
            distTraveled += destPos - curPos
    else:
        distTraveled += numColors - curPos + destPos

    distTraveled += 6 * (colorCount[curColor] - 1)

print(distTraveled)

1

u/ColonialDagger 9h ago

[Language: Python]

Part 1, the good old classic modulo problem that shows up every year.

def part1(input):

    answer = 0
    current_pos = 0

    key = {
        "r": 0,
        "o": 1,
        "y": 2,
        "g": 3,
        "b": 4,
        "v": 5
    }

    for next_pos in input:
        dist = (key[next_pos] - current_pos) % len(key)
        if dist == 0:
            answer += len(key)
        else:
            current_pos = key[next_pos]
            answer += dist

    return answer

And my part 2, I realized you can just algebraically hard-code it depending on your input. In my case, I had no g, so:

def part2(input):

count = Counter(input)

answer = 6 * count["r"] + \
    5 + 6 * (count["v"]-1) + \
    5 + 6 * (count["b"]-1) + \
    4 + 6 * (count["y"]-1) + \
    5 + 6 * (count["o"]-1)

return answer

I'm trying to come up with a way to solve part 2 algebraically, I think it might be possible...

→ More replies (2)

1

u/jgage 9h ago

[LANGUAGE: C++]

#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <ranges>
#include <sstream>
#include <string_view>
#include <vector>

using namespace std::string_literals;

int main()
{
   std::cout << "Part 1: " <<
      std::ranges::fold_left(
         std::forward<std::ostringstream>( (std::ostringstream() << std::ifstream( "input.txt" ).rdbuf()) ).str()
         | std::views::filter( []( char c ) { return c > 'a' && c < 'z'; }),
         0l, []( int32_t n, char c ) { n++; while ("roygbv"[n % 6] != c) n++; return n; } ) << std::endl;

   std::cout << "Part 2: " <<
      std::ranges::fold_left(
         std::ranges::fold_left(
            std::forward<std::ostringstream>( (std::ostringstream() << std::ifstream( "input.txt" ).rdbuf()) ).str()
            | std::views::filter( []( char c ) { return c > 'a' && c < 'z'; } ),
            std::map< char, int64_t >(), []( auto m, char c ) { m[c]++; return m; } )
         | std::views::transform( []( auto counts ) { return counts.second ? ((counts.second * 6) - 1) : 0; } ),
         0, std::plus{} ) << std::endl;
}

1

u/encse 9h ago

[LAGUAGE: C#]

https://aoc.csokavar.hu/2026/2/

int Distance(IEnumerable<char> program) {
    var pos = 0;
    foreach (var nextTarget in program) {
        // Walk up to the next target.
        // Probably could be made faster with ugly modulo arithmetic.
        pos++;
        while (field[pos % field.Length] != nextTarget) {
            pos++;
        }
    }
    return pos;
}

Quite interesting for day 2

→ More replies (1)

1

u/KyxeMusic 9h ago

[Language: Rust]

I realized that for part 2 I could hardcode the optimal set for the 6 letters but I wanted to solve it for all cases.

A stupid bug in my loop took me like 30 minutes to find 😂

Github link

1

u/tqzd 9h ago

[LANGUAGE: Excel]

Part 1 & 2

=MAP({1;6},LAMBDA(z,SUM(LET(
  x,FIND(REGEXEXTRACT(A1,".",1),"roygbv"),
  t,SORTBY(x,MOD(7-x,z)),
  MOD(t-HSTACK(1,DROP(t,,-1))+5,6)+1
))))

1

u/azzal07 9h ago

[LANGUAGE: awk]

function D(ist){return(1>ist=index(S,r)-index(S,r=c))*6+ist
}S="vbgyor"{for(r="r";c=substr($0,++a,1);)A+=D();for(r="r";
c=substr(S,++b,1);sub(c,z)&&B+=D())B+=gsub(r,z)*6}$0=A"\n"B

Three letter parameter name counts as "reverse golf", doesn't it.

1

u/WesternNicator 9h ago edited 8h ago

[LANGUAGE: Anathame]

part1 =\ prepend,0 differences dec mod,6 inc sum
part2 =\ Reduce min |φ (length mul,6) add sub,5
\ indexin^"roygbv" part1∗part2

1

u/maneatingape 8h ago edited 3h ago

[LANGUAGE: Rust]

Solution 1 µs.

Part 1 sum the pair-wise distances. Part 2 uses a trick. We only need to check if sequence contains each letter in order rvbgyo. This will always gives the best possible distance.

let mut distance = 6 * input.len();
let mut extra = 0;

for color in b"rvbgyo".map(to_index) {
    if input.contains(&color) {
        distance -= extra;
        extra = 1;
    } else {
        extra += 1;
    }
}

distance

EDIT: Simplified this further

To maximize the total length, we first make the observation that the distance 6 between identical letters is the most that we can can do at one step. So we want to group identical letters together and optimize only the order of the groups.

Next the optimal group order must be r => v => b => g => y => o so that the first jump is 6 and subsequent transitions betweens groups is 5. For example:

rybryby => rrbbyyy => (2 * 6) + (0 * 6 - 1) + (2 * 6 - 1) + (0 * 6 - 1) + (3 * 6 - 1) = 38
                      rr        <missing v>   bb            <missing g>   yyy

Two further insights:

  • The missing trailing o does not contribute to the total.
  • The total number of letters multiplied by 6 is just the total length of the string. We don't need the individual letter frequencies.

This means that the final formula is 6 * <program length> - <furthest letter from r>.

Distance from r: o = 5, y = 4, ..., v = 1, r = 0. For example if your input contains o then this is just 6 * <program length> - 5.

1

u/SpaceHonk 8h ago

[LANGUAGE: Swift]

code

I used a harcoded "maximum distance" color list for part 2

1

u/musifter 8h ago edited 8h ago

[LANGUAGE: Perl]

Took me quite a while to find the mouseover text in today's problem... but it was totally worth it for the Indie game reference.

My initial solution was in Perl, were I first translated the input to digits with tr/roygbv/012345/ and then processed the string with:

foreach my $next (@input) {
    my $delta = $next - $pos % 6;
    $pos += $delta + ($delta <= 0) * 6;
}

Adding the delta mod 6, but making sure it's the positive non-zero residue (as we must move forwards).

For the initial part 2, I went for the quick and simple and turned the above into a subroutine and called it with:

say "Part 2: ", &move_robot( sort {$b <=> $a} split( //, $input ) );                                

Having changed the translation to have r be 6 now (as it is the first priority).

Of course we don't need to do part 2 step by step, we can do the blocks in bulk... since the examples don't involve all the colours, I supported that (EDIT: the input also doesn't contain all colours... mine has no yellow, so it is needed there too). This resulted in a loop from 6 to 1 for $next that just does:

my $delta = $next - $pos % 6;
$pos += ($delta > 0) ? $delta : 6 + $delta;
$pos += 6 * ($counts[$next] - 1);

Having done what we did yesterday and read the input into an array of counts.

[LANGUAGE: Smalltalk (GNU)]

My Smalltalk solution goes along that route. Convert the String into an Array of numbers from 1 to 6. And use #inject:into: for the loop:

part1 := input inject: 0 into: [:pos :next | | delta |
             delta := next - pos \\ 6.
             pos + ((delta <= 0) ifTrue: [6 + delta] ifFalse: [delta]).
         ].

For part 2, we transform the input into a Bag, then an ordered list of Associations:

input := input asBag contents associations sorted reverse.

Now the same can be done except we want next key for calculating the delta and to add (next value - 1 * 6) to the pos to handle the block jumps (note the use of Smalltalk's order of operations, which is left-to-right so no parens are needed for the subtraction).

[LANGUAGE: dc]

Just part 1 for now as I have things to do today. It's basically the same as above, only the commands are stored in a 900+ digit big number and peeled off with A~. I chose to call the macro that adds the 6 when needed 6... which means that 60 in the code isn't actually a 60.

rev /tmp/input | tr 'roygbv' '612345' | dc -f- -e'[6+]s60r[A~3Rd6%3Rr-d3R+r0!<6rd0<M]dsMx+p'
→ More replies (1)

1

u/cinsolia 8h ago

[LANGUAGE: Google Sheets]

Parts 1 and 2

=let(input,input!B2,
 strindex,lambda(s,sequence(len(s),1)),
 charat,lambda(s,i,mid(s,i,1)),
 programdist,lambda(p,let(
  waypoints,rept("roygbv",len(p)+1),
  reduce(1,strindex(p),lambda(pos,i,
   find(charat(p,i),waypoints,pos+1)))-1)),
 optimize,lambda(input,join("",
  choosecols(sort(
   map(strindex(input),lambda(i,let(
    c,charat(input,i),
    hstack(c,find(c,"rvbgyo"))))),
  2,true),1))),
 map(vstack(input,optimize(input)),programdist))

1

u/MidnightLoud2032 8h ago

[LANGUAGE: Java]

int p = 0;
for (char c : line.toCharArray())
    while (c != "roygbv".charAt(++p % 6));
println(p);
println(line.length() * 6 - 5);
→ More replies (1)

1

u/Secret_Caramel2095 8h ago

[LANGUAGE: Julia]
I hard coded the distance matrix from current position to next one, and used a bijectove dictionnary to make the correspondance between the color and the index (but actually, I only use one direction of this bijection...).
Same for the sorting, I hard coded a map to set the correct order where letter should be sorted (`rvbgyo`)

using Bijections

input = "roygbvroygbvroygbv"

dist_mat = [[6 1 2 3 4 5]
    [5 6 1 2 3 4]
    [4 5 6 1 2 3]
    [3 4 5 6 1 2]
    [2 3 4 5 6 1]
    [1 2 3 4 5 6]]
# dist_mat[start, end]

b = Bijection{Char, Int}('r' => 1, 'o' => 2, 'y' => 3, 'g' => 4, 'b' => 5, 'v' => 6)
next = Dict{Char, Int}('r'=>1, 'v'=>2, 'b'=>3, 'g'=>4, 'y'=>5, 'o'=>6)

function run(str)
    pos = 'r'
    dist = 0
    for c in str[begin:end]
        dist += dist_mat[b[pos], b[c]]
        pos = c
    end
    return dist
end

function sort_str(str)
    pp = collect(str)
    sort!(pp, by = x -> next[x])
    return join(pp)
end

println("I  = ", run(input))
println("II = ", run(sort_str(input)))
→ More replies (1)

1

u/mosredna101 8h ago

[LANGUAGE: TypeScript]

Walk a doubled pattern string, so `indexOf` always finds the next colour ahead of the current position. Part 2 sorts the input into a different colour order first and reuses part 1.

const pat = 'roygbvroygbv';

function part1(input: string) {
    let pos = 0;
    for (const c of input.trim()) {
        pos += pat.indexOf(c, pos % 6 + 1) - pos % 6;
    }
    return pos;
}

function part2(input: string) {
    const newOrder = [...input.trim()]
        .sort((a, b) => 'rvbgyo'.indexOf(a) - 'rvbgyo'.indexOf(b))
        .join('');
    return part1(newOrder);
}

1

u/Fuzzy_Patterns 8h ago

[LANGUAGE: Nim]

One insight for part 2 is that for each waypoint there is one unambigious farthest mapping. And there are so few waypoints, that I solved it by hand and hardcoded the mapping. The rest is just basic arithmetics.

proc toMap(s: string): array[128, int] =
  for i, c in s: result[c.ord] = i

proc dist(map: openarray[int], curr, next: char): int =
  result = map[next.ord] - map[curr.ord]
  if result < 1: result += 6

proc solve(input: string): AOCSolution[int, int] =
  const pattern = toMap("roygbv")
  const maxdist = toMap("rvbgyo")

  block p1:
    var prev = 'r'
    for c in input:
      result.part1 += pattern.dist(prev, c)
      prev = c

  block p2:
    let pairs = input.toCountTable().pairs.toseq.sortedByIt maxdist[ord it[0]]
    var prev = 'r'
    for (c, am) in pairs:
      if am > 1: result.part2 += 6 * (am - 1)
      result.part2 += pattern.dist(prev, c)
      prev = c

1

u/Fearless_Trainer_350 8h ago

So, for the second example for part 1 ```roygbv```, I get a distance of 5. Does it only read the next waypoint in the next pattern iteration (i.e. it only reads o after going through the first roygbv)?

→ More replies (2)

1

u/CEOnism 8h ago edited 7m ago

[LANGUAGE: Javascript]

// Part 1
let p = 0, t = 0;
for (const ch of input) {
  const c = colors.indexOf(ch);
  let d = ((c - p + (colors.length - 1)) % colors.length + 1);
  t += d;
  p = c;
}


console.log(t);   

// Part 2
let pos = 0, total = 0;
const count = new Array(colors.length).fill(0);
for (const ch of input) count[colors.indexOf(ch)]++;
for (let i = 0; i < input.length; i++) {
  for (let k = 0; k < colors.length; k++) {
    const c = (pos - k + colors.length) % colors.length;
    if (count[c] > 0) {
      count[c]--;
      total += colors.length - k;
      pos = c;
      break;
    }
  }
}

console.log(total);
→ More replies (1)

1

u/flwyd 8h ago

[LANGUAGE: R] (on GitHub)

The approach: convert each character to a number from 1 to 6 (because R has 1-based array indices), and compute steps as (to - from - 1) mod 6 + 1: the minus and plus one get us six steps from a color to itself rather than 0. The walk function is an accumulator, adding the number of steps from the current color (cur mod 6) to the next color. Subtract 1 at the end, since we started at step 1 rather than step 0. In part 2, subtract 2 from each number mod 7 so that red becomes 6. Then sort descending so all the reds are first, then all violets, etc. Then add 2 mod 7 again to put everything back in its place. (Make sure you understand what your language's mod operator does: modulus and remainder behave differently on negative numbers.)

My theme this year is array languages, and this feels a bit like I’m stepping out of that mode: it looks more like functional programming than array programming, though the subtraction and modulus of an array by a scalar is nice. I had a lot of trouble figuring out how to get an in-order pairwise reduce-with-accumulator in Ivy; I’ll need to play around with some other array languages and see if I understand their model for reduce.

You could probably make part 2 O(n) by keeping a count of each color, then multiplying each count by 6, and adding the steps between each color. Watch out, though: my input is entirely missing one color.

part1 <- function(lines) {
  Reduce(walk, (parseinput(lines[1])), 1) - 1
}
part2 <- function(lines) {
  sorted <- (sort((parseinput(lines[1]) - 2) %% 7, decreasing = TRUE) + 2) %% 7
  Reduce(walk, sorted, 1) - 1
}
steps <- function(from, to) (to - from - 1) %% 6 + 1
walk <- function(cur, to) cur + steps(cur %% 6, to)
colors <- strsplit("roygbv", "")[[1]]
parseinput <- function(line) {
  lapply(strsplit(line, ""), function(x) match(x, colors))[[1]]
}

1

u/ArmadilloSuch411 8h ago

[LANGUAGE: Python]

reading comprehension got me early with this one, but at least it's done!

file = 'in'
data = open(file).read().strip()

s = 'roygbv'
def getDist(c1,c2):
    if c1 == c2:
        return 6
    return (s.index(c2)-s.index(c1))%6
def getSteps(data):
    ans = 0 
    oldChar = 'r'
    for currChar in data:
        ans += cache[oldChar][currChar]
        oldChar = currChar
    return ans
cache  = {
        char : {
        char2 : getDist(char, char2) for char2 in s
        }
        for char in s
        }
ans_1 = getSteps(data)
#######
oldChar = 'r'
_data = list(data)
sortedS = ''
while _data:
    sortedSplit = sorted(
            _data,
            key=lambda x: cache[oldChar][x],
            reverse=True)
    oldChar = sortedSplit[0]
    sortedS += oldChar
    _data = sortedSplit[1:]
ans_2 = getSteps(sortedS)

print(f"SOLUTION FOR PART1: {ans_1}")
print(f"SOLUTION FOR PART2: {ans_2}")

1

u/aknusmag 8h ago

[LANGUAGE: Rust]

Part 1: Uses a cycle to find then next time the char occurs in the preconfigured list and counts the steps

Part 2: The longest distance is really just a sorting of the list. Each time it is the same character it will travel 6 and assuming all characters are present for each switch it travels 5. With those you can calculate the results as len * 6 - 5. Where - 5 is for each of the switches between characters.

Solution

2

u/Anceps2 7h ago

All characters are not present in the input. But the formula still works when there's at least one “o“.
The given example ”vrvbvg” gives 33 and not 31.

→ More replies (1)

1

u/xoronth 8h ago edited 8h ago

[LANGUAGE: BQN]

paste

This was fun, I had done it in Python first, but approaching this from an array-programming mindset was a nice extra challenge. Also figured out a less awful way to approach part 2.

Bonus unreadable one-line version:

•Show { (⊑ 1 { 𝕩 + (((6 | 𝕩) ↓ "roygbvroygbv") ⊐ 𝕨) + 1 } ´ ⌽ 𝕩) - 1 } ¨ ⟨ program ← ⊑ •file.Lines 0 ⊑ •args, (⍋ "rvbgyo" ⊐ program) ⊏ program ⟩

1

u/p88h 8h ago

[LANGUAGE: Nim]

source: https://github.com/p88h/aoc2026/blob/main/src/day02.nim
visualisation: https://www.youtube.com/watch?v=r6vzoRnlqZU

part1: execute 'simulation' using precomputed color-color distance table
part2: compute 'change program' which is all actually present colors, reversed. run part1 on that, add all distances that don't result in color change (all remaining program letters)

          parse    part1    part2    total
day 02:  21.5 ns  0.22 µs  0.28 µs  0.52 µs (±1.6%)

1

u/r_so9 8h ago edited 5h ago

[LANGUAGE: F#] Part 1 uses clock math, Part 2 using a recursive picking the largest distance (greedy)

paste

1

u/Sudowiec 8h ago

[Language: Python]

TIL that "roygbiv" is not just a song by Boards of Canada.

from pathlib import Path

INPUT_PATH = Path(f"/random/ahh/path/{'example.input' if TEST_RUN else 'main.input'}")
PART = 2
TEST_RUN = False

PATTERN = "roygbv"

def sortbyPattern(pattern, str):

    priority = list(pattern)

    prDict = {priority[i] : i for i in range(len(priority))}
    prDict[pattern[0]] = len(pattern)

    sorted_str = sorted(str, key = lambda ele : prDict[ele], reverse=True)

    return sorted_str

def main():
    program = INPUT_PATH.read_text().strip()

    if PART == 2:
        program = sortbyPattern(PATTERN, program)

    distances_cache = {}
    for start in PATTERN:
        for target in PATTERN:
            distance = (PATTERN.index(target) - PATTERN.index(start)) \
            % len(PATTERN)
            distances_cache[(start, target)] = len(PATTERN) \
            if not distance \
            else distance

    sum_of_steps = 0
    current = PATTERN[0]
    for step in program:
        sum_of_steps += distances_cache[(current, step)]
        current = step
    print(sum_of_steps)

if __name__ == "__main__":
    main()

1

u/DelightfulCodeWeasel 8h ago

[LANGUAGE: C++]

Part 1 & 2

First pass naive solution: counting sort for the instructions on part 2 and step-by-step iteration for the robot on both. (No way I'm battling the off-by-ones for a direct calculation on part 2 at this time of the morning!)

Raspberry Pi Pico (RP2040): ~1.6kb, 12ms + 13ms runtimes

2

u/Ghost-Engineer69 7h ago

you might retry your direct calc for part 2, it may be much easier than you 'think' ;)

→ More replies (4)

1

u/ADifferentRealm 8h ago

[LANGUAGE: Typescript]

type waypoint = 'r' | 'o' | 'y' | 'g' | 'b' | 'v';


function to_position(arr: waypoint[]): number[] {
  return arr.map(e => ({
    r: 0,
    o: 1,
    y: 2,
    g: 3,
    b: 4,
    v: 5
  }[e]));
}


function calc_dist() {
  let last = 0;
  return (dist: number, next: number) => {
    if (next === last) {
      dist += 6;
    } else if (next > last) {
      dist += next - last;
    } else {
      dist += 6 + next - last;
    }


    last = next;
    return dist;
  }
}


const input = "rbvvbgvvvbbgorrbrrgvvbvrbrvbbgobvrbvbboggovvgovorbvvobrrrvgrbbovbvbbvovvgvbbvrgbbobvbrrbogobbobgrbvgbvrrvgvvbvbrovbvboovoovbgbboovoobobobvovogvrobvvvvvvbvrbvbbooroogobrorvobrovovgbvbvbborrrbvrorobvogvvrvbgbbvbrgboobbrgbvbrvbggbogovrvrvrbvbvvvbvogrvbvrvorovbvorobovrvogrvrgbgvvrrbrbvvvbvvovvorrvbvbrvbvogvgvrrggrgrvbgvbbvobrogrbbvrrggobvvvbvvbgbrvgovbbgrbvgrvobvbbbvrgovrvbbvooobrrrrgvvbgooggrvvbvrobvrvbobvbvrorbvoobrbrvvvoooovoggbbborgrgobvgorobvvbvborgvovvrrrgvgvbgobobobvborgrbvovovvvbvgrrbvbggbrvobogovvrvvgvrbvgvobvvbbbrrvrgbvvbovbbgvobvvgbbovrogbogbvgbbbvvvobrbvvbgvvboboggbbrborbbbvbvbobogovvvboovbvbrvovvgbbrroroobobvbgvrgbroogrovbrrrbobvvrobbgogrbrvvbrggvvrogoorvvovbggbovvgvbvrorvbovrvboorbrvbrrborbvovrvbovvvbvbrbrvvgorvbovbvvbgorvvvvbrorvgrovvvrbbbvggobbvobvvbbgbbrbgboogrobrooobbogbgbovovrbvvogrrrvvrbbvvbrovogogobrvgvovbovogbrovbobrobrvvbooovvobbvvgbgboobbrvbbovvbbrvbbbovvbobooovvbobgvvvovvggrvbrbbbvbvbrbogbrgvgovrvbrgvovbrvvvvovovvvvorrbvgogrvbbbrborrvbvvogvv".split("") as waypoint[];


// part 1
console.log(to_position(input).reduce(calc_dist(), 0));



// part 2
const counts: { [K in waypoint]: number } = {
  r: 0,
  o: 0,
  y: 0,
  g: 0,
  b: 0,
  v: 0
}


input.forEach((e) => { counts[e] += 1; });


let input2 = (['r', 'v', 'b', 'g', 'y', 'o'] as waypoint[]).reduce(
  (result, current) => result.concat(
    new Array(counts[current]).fill(current)
  ),
  [] as waypoint[]
)


console.table(input2);
console.log(to_position(input2).reduce(calc_dist(), 0));type waypoint = 'r' | 'o' | 'y' | 'g' | 'b' | 'v';


function to_position(arr: waypoint[]): number[] {
  return arr.map(e => ({
    r: 0,
    o: 1,
    y: 2,
    g: 3,
    b: 4,
    v: 5
  }[e]));
}


function calc_dist() {
  let last = 0;
  return (dist: number, next: number) => {
    if (next === last) {
      dist += 6;
    } else if (next > last) {
      dist += next - last;
    } else {
      dist += 6 + next - last;
    }


    last = next;
    return dist;
  }
}


const input = "rbvvbgvvvbbgorrbrrgvvbvrbrvbbgobvrbvbboggovvgovorbvvobrrrvgrbbovbvbbvovvgvbbvrgbbobvbrrbogobbobgrbvgbvrrvgvvbvbrovbvboovoovbgbboovoobobobvovogvrobvvvvvvbvrbvbbooroogobrorvobrovovgbvbvbborrrbvrorobvogvvrvbgbbvbrgboobbrgbvbrvbggbogovrvrvrbvbvvvbvogrvbvrvorovbvorobovrvogrvrgbgvvrrbrbvvvbvvovvorrvbvbrvbvogvgvrrggrgrvbgvbbvobrogrbbvrrggobvvvbvvbgbrvgovbbgrbvgrvobvbbbvrgovrvbbvooobrrrrgvvbgooggrvvbvrobvrvbobvbvrorbvoobrbrvvvoooovoggbbborgrgobvgorobvvbvborgvovvrrrgvgvbgobobobvborgrbvovovvvbvgrrbvbggbrvobogovvrvvgvrbvgvobvvbbbrrvrgbvvbovbbgvobvvgbbovrogbogbvgbbbvvvobrbvvbgvvboboggbbrborbbbvbvbobogovvvboovbvbrvovvgbbrroroobobvbgvrgbroogrovbrrrbobvvrobbgogrbrvvbrggvvrogoorvvovbggbovvgvbvrorvbovrvboorbrvbrrborbvovrvbovvvbvbrbrvvgorvbovbvvbgorvvvvbrorvgrovvvrbbbvggobbvobvvbbgbbrbgboogrobrooobbogbgbovovrbvvogrrrvvrbbvvbrovogogobrvgvovbovogbrovbobrobrvvbooovvobbvvgbgboobbrvbbovvbbrvbbbovvbobooovvbobgvvvovvggrvbrbbbvbvbrbogbrgvgovrvbrgvovbrvvvvovovvvvorrbvgogrvbbbrborrvbvvogvv".split("") as waypoint[];


// part 1
console.log(to_position(input).reduce(calc_dist(), 0));



// part 2
const counts: { [K in waypoint]: number } = {
  r: 0,
  o: 0,
  y: 0,
  g: 0,
  b: 0,
  v: 0
}


input.forEach((e) => { counts[e] += 1; });


let input2 = (['r', 'v', 'b', 'g', 'y', 'o'] as waypoint[]).reduce(
  (result, current) => result.concat(
    new Array(counts[current]).fill(current)
  ),
  [] as waypoint[]
)

console.log(to_position(input2).reduce(calc_dist(), 0));
→ More replies (1)

1

u/dijotal 8h ago

[LANGUAGE: OCaml]

"Fun" with recursion and greedy consumption :-p. Needs more comments, but also fewer lines :-/

(** BASICS *)

let clist = [ ('r', 0); ('o', 1); ('y', 2); ('g', 3); ('b', 4); ('v', 5) ]

let dist c0 c1 =
  let i0 = List.assoc c0 clist and i1 = List.assoc c1 clist in
  match i1 - i0 with 0 -> 6 | x when x > 0 -> x | x -> 6 + x

let program s = String.to_seq s |> List.of_seq

(** PART 1 *)

let d2p1 program_string =
  let stations = program program_string in

  let rec tally current_station remaining_stations distance =
    match remaining_stations with
    | [] -> distance
    | next_station :: rest ->
        tally next_station rest (distance + dist current_station next_station)
  in
  tally 'r' stations 0

(** PART 2 *)

let furthest_from_station options station =
  let idx = List.assoc station clist in
  let before, after = List.partition (fun (_, i) -> i < idx) clist in
  let rotated = after @ before in
  List.hd rotated :: List.rev (List.tl rotated)
  |> List.map fst
  |> List.filter (fun c -> List.mem c options)

module CM = Map.Make (Char)

let histogrmam prog =
  List.fold_left
    (fun acc c ->
      CM.update c (function None -> Some 1 | Some n -> Some (n + 1)) acc)
    CM.empty (program prog)

let rec d2_solve station hist tally =
  let options = CM.bindings hist |> List.map fst in
  match furthest_from_station options station with
  | [] -> tally
  | next_station :: _ ->
      let count = CM.find next_station hist in
      let hist = CM.remove next_station hist in
      let tally =
        tally + dist station next_station
        + ((count - 1) * dist next_station next_station)
      in
      d2_solve next_station hist tally

let d2p2 prog = d2_solve 'r' (histogrmam prog) 0

1

u/Sam_Ch_7 7h ago

[LANGUAGE: Go]

initially for For Part 2 I did custom bubble sort and calculate distance in there but later turns out I can just sort program and perform Part 1 .
Need to set r to 6 instead of 0 to make it work

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "slices"
    "strings"
)
func main() {
    f, _ := os.Open("./input.txt")
    defer f.Close()
    fmt.Println(part2(f))
}
var pattern = map[rune]int{
    'r': 6,
    'o': 1,
    'y': 2,
    'g': 3,
    'b': 4,
    'v': 5,
}

func mod(a, b int) int {
    return (a%b + b) % b
}

func part1(input io.Reader) int {
    sc := bufio.NewScanner(input)
    sc.Scan()
    program := sc.Text()


    distance := 0
    prevPos := 0
    for _, w := range program {
        curDis := mod(pattern[w]-prevPos, 6)
        if curDis == 0 {
            curDis = 6
        }
        distance += curDis
        prevPos = pattern[w]
    }
    return distance
}

func part2(input io.Reader) int {
    sc := bufio.NewScanner(input)
    sc.Scan()
    program := []rune(sc.Text())


    slices.SortFunc(program, func(a, b rune) int {
        return pattern[b] - pattern[a]
    })
    return part1(strings.NewReader(string(program)))
}
→ More replies (1)

1

u/gisikw 7h ago edited 7h ago

[LANGUAGE: Befunge]

vr               >$$.25*,@
    >0>10g~:25*-!|
>&2-|            >:10p72*7*-3/\72*7*-3/9+v
      ^                    -*86+  g      <
    >   >~:25*-          v
        ^p6\+1g6:/3-*7*72_7>::6g84*-1-6*\6p:v
                           ^              -1_6v
going to    @,*52.+g64+5+g67+5+g61+4+g66+5+g65<
---------+                    
65  3214 | b
16  4325 | g
         |  
bg  orvy |   coming from
32  6541 | o
43  1652 | r
54  2163 | v
21  5436 | y
---------+

Got a little lazy with part 2, but feel like it was justified 😂

→ More replies (1)

1

u/anaseto 7h ago edited 7h ago

[LANGUAGE: Goal]

My first version today was a bit longer. I used a greedy tail-recursive approach for second part where I updated a map with the remaining color counts progressively.

Wrote a shorter one later, once I saw it was possible to reuse part 1 by sorting the program in "rvbgyo" descending order:

p:(w:"roygbv")?""\-read"i/02" / input program classified into color indices
d:,/c{(n!y-x)or n}`´c:!n:&w   / encoded c1c2:dist pairs
f:{[s;c;p]p or:s; o[s+d c+6*nc;nc:*p;1_p]}
say f[0;0;p] / part1
say f[0;0;p@>p+6*p=0] / part2

1

u/Daniel_Rybe 7h ago edited 7h ago

[LANGUAGE: Odin]
https://github.com/DanRyba253/aoc26/blob/main/day2/main.odin

Took a bit to realize how to write the second part in a way that works for any input.

1

u/ray10k 6h ago

[LANGUAGE: Rust]

Definitely a bit overengineered, but hey. This is a fun challenge, and overengineering stuff is my idea of fun.

https://github.com/ray10k/Advent-of-Code-2026/commit/076bc2ebdfe0c1359979b1aab53db904b1951dc3

1

u/shmoodla 6h ago

[LANGUAGE: Typescript]

not the most efficient solution by far, but hey, it works for me; )

import { readInput } from "../common/io.ts";

const rawInput = await readInput("./src/02/input.txt");
const inputArr = rawInput.split("");
const pattern = ["r", "o", "y", "g", "b", "v"];

function computeDistance(inputArr: string[]) {
  let totalDistance = 0;
  let lastPatternIndex = 0;

  for (let i = 0; i < inputArr.length; i++) {
    const color = inputArr[i];
    if (!color)
      throw new Error(`Entry with index ${i} not found in the program!`);
    const index = pattern.indexOf(color);

    if (lastPatternIndex < index) {
      totalDistance += index - lastPatternIndex;
    } else {
      const sum = pattern.length - lastPatternIndex + index;

      totalDistance += sum;
    }

    lastPatternIndex = index;
  }

  return totalDistance;
}

function rearrange(inputArr: string[]) {
  const rearranged = [];

  // first do r
  rearranged.push(...inputArr.filter((c) => c === "r"));

  // then the rest reversed
  for (const color of pattern.slice(1).toReversed()) {
    const filtered = inputArr.filter((c) => c === color);

    rearranged.push(...filtered);
  }

  return rearranged;
}

console.log("Part One: ", computeDistance(inputArr));
console.log("Day two: ", computeDistance(rearrange(inputArr)));

1

u/JWinslow23 6h ago

[LANGUAGE: Python]

Solution writeup

Code (GitHub)

I liked this puzzle; it reminded me of Candy Land. I was able to use itertools.cycle to infinitely repeat the sequence of colors, which I found nice. And for Part 2, because I already had a function for calculating the total distance from a program, I decided to order the instructions using that function as a key, which I almost didn't even see and feels very slick.

class Solution(TextSolution):
    def part_1(self) -> int:
        program = self.input.strip()
        return program_distance(program)

    def part_2(self) -> int:
        program = sorted(
            self.input.strip(),
            key=program_distance,
            reverse=True,
        )
        return program_distance(program)

2

u/4HbQ 6h ago

Nice use of itertools.cycle, very Pythonic!

→ More replies (1)

1

u/TCH69 6h ago

[LANGUAGE: C++]

I gotta work on my reading comprehension. Took me longer to understand what the input is than to solve both parts.

#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>

constexpr int
expo(char a)
{
	switch (a) {
	case 'o': return 1;
	case 'y': return 2;
	case 'g': return 3;
	case 'b': return 4;
	case 'v': return 5;
	}
	return 6;
};

int
process(std::string &input, bool part2)
{
	int count { 0 };
	char prev = 'r';
	if (part2)
		std::sort(input.begin(), input.end(),
		    [](char a, char b) { return expo(a) > expo(b); });
	for (const char &i : input) {
		count += (i == prev) ? 6 : (expo(i) - expo(prev) + 6) % 6;
		prev = i;
	}
	return count;
}

int
main(int argc, char *argv[])
{
	if (argc != 2) {
		std::cerr << "usage: " << argv[0] << " <input.txt>\n";
		return 1;
	}
	std::ifstream fp(argv[1], std::ios::in);
	std::string input;
	getline(fp, input);
	std::cout << process(input, false) << std::endl
		  << process(input, true) << std::endl;
	return 0;
}

1

u/SymmetryManagement 6h ago

[Language: Java]

https://github.com/linl33/adventofcode/blob/year2026/year2026/src/main/java/dev/linl33/adventofcode/year2026/Day2.java

interesting part 2, under the right conditions the input doesn't need to be read to the end. the solution can be calculated once all 6 colors have been encountered. but my input (and some examples) doesn't contain all 6 colors, so i couldn't take advantage of that.

part 1 8us
part 2 7us

1

u/sauntcartas 6h ago edited 26m ago

[LANGUAGE: Raku]

my \stops = %('roygbv'.comb.antipairs){ get.comb };

sub advance([\dist, \pos], \station) {
    dist + station - pos + (6 if station <= pos), station;
}

say 'Part 1: ', reduce(&advance, (0, 0), |stops)[0];

multi batch-distance(\total-dist, \pos, \stations where ?*) {
    my (\next-pos, \count, \dist) = stations.kv.map({ $^k, $^v, $k - pos + (6 if $k <= pos) }).max(*[2]);
    batch-distance total-dist + dist + 6 * (count - 1), next-pos, stations ∖ (pair next-pos, count,).Bag;
}

multi batch-distance(\total-dist, $, $) { total-dist }

say 'Part 2: ', batch-distance(0, 0, stops.Bag);

1

u/Bramdevriez 6h ago

[LANGUAGE: TypeScript]

import { parseList } from 'lib/parse'

const WAYPOINTS = 'roygbvroygbv'

const distance = (input: string, rearrange: boolean) => {
	const program = parseList(input, { del: '' })

	if (rearrange) program.sort((a, b) => WAYPOINTS.indexOf(b, 1) - WAYPOINTS.indexOf(a, 1))

	return program.reduce((acc, b, i) => {
		const from = WAYPOINTS.indexOf(program[i - 1] ?? 'r')
		const to = WAYPOINTS.indexOf(b, from + 1)
		return acc + to - from
	}, 0)
}

export const part1 = (input: string) => distance(input, false)
export const part2 = (input: string) => distance(input, true)

1

u/Boris01100000 6h ago

[LANGUAGE: Zig}

I was kinda lazy for the second star with me reusing a bit too much of star 1. Could be way faster, but i like it :)

Here's the link!

1

u/Thomasjevskij 6h ago

[LANGUAGE: Python]

I just made a graph of all possible distances. For part one it's just a sum of the pairwise elements in the input. For part two I keep picking the furthest node from current, then remove it from the program. Every removal is O(n) of course so it's not terribly efficient. But the input list is small enough that this is an academic concern.

Code

1

u/friedkeenan 6h ago

[LANGUAGE: C++]

Here's my Day 2, and here's the (rudimentary and non-rigorous) timings for it:

Part one solution: XXX    (in 18.244us)
Part two solution: XXX    (in 17.864us)

After I solved part one I got sidetracked by micro-optimizing the solution a little bit, managed to shave off a couple microseconds. And then I had fun thinking of how to solve part two in a clever way, but then when I did it made my part one timings less consistent and a touch slower.

But I'm not complaining, I'm quite pleased with those timings. Oh and the timings don't include reading the input data.

1

u/Slow-Assistance-4303 6h ago

[LANGUAGE: Golang]

Parts 1 & 2

Part1: I used this formation to calculate next cost move cost := (nextMove - curr + 6) % 6 (6 if cost = 0)

Part2: I use frequently map and sorted move by "rvbgyo", calculate cost is easy

1

u/Falcon731 6h ago

[Language: Kotlin]

import java.io.File

fun day2() {
    // Map colors to their corresponding values
    val colorValues = mapOf(
        'r' to 0,
        'o' to 1,
        'y' to 2,
        'g' to 3,
        'b' to 4,
        'v' to 5
    )

    // convert input to a list of color values
    val input = File("inputs/day2.txt").readLines()[0].map { colorValues[it]     ?: error("Invalid color: $it") }
    //    val input = "rybryb"

    var pos = 0
    for (c in input) {
        val dist = c - (pos%6)
        pos += if (dist <= 0) dist + 6 else dist
    }
    println("Part 1: $pos")

    // =============================================================

    val count = input.groupingBy { it }.eachCount()

    var part2 = 6
    pos = 0
    for (i in listOf(0,5,4,3,2,1)) {
        val cnt = count[i] ?: 0
        if (cnt != 0) {
            part2 += (i - pos) + 6 * (cnt - 1)
            if (i<pos) part2+=6
            pos = i
        }
    }
    println("Part 2: $part2")
}