r/adventofcode • • 18h 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.

25 Upvotes

578 comments sorted by

2

u/morgoth1145 18h ago edited 18h 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 18h ago edited 18h ago

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

→ More replies (1)

2

u/musifter 16h ago edited 1h 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'

EDIT: And part 2.

tr 'roygbv' '612345' </tmp/input | dc -f- -e'[A~d;c6+r:cd0<L]dsLx[d;cr_4R++r0r]sJd6[d;c0<Jr1-r1-d0<M]dsMx+rp'

To do this well in dc I did it as a state machine. I first got the counts of each number/colour (multiplied by 6). Then I start pos=count[6] and run through the table from 5 to 1. There's a counter for how much to subtract for the amount missing from the first jump in each block that gets reset whenever there's a block. Simplifying the calculation down to:

$sub++;
if ($counts[$next]) {
    $pos += $counts[$next] - $sub;
    $sub = 0;
}

EDIT: A little cleanup and reordering of things on the stack to golf part 2 down a bunch of strokes.

2

u/daggerdragon 4h ago

!!! Your post made it through the filters and modqueue without me needing to approve it! And you seem to be un-banned from Reddit! You're a little late past Halloween, but welcome back to the land of the living! :D

2

u/flwyd 13h ago

[LANGUAGE: Ivy] (on GitHub)

I started implementing this in Ivy, got stuck on the / reduce modifier, and implemented the same logic in R. Returning to Ivy and playing with the same semantics in APL, I realized that my confusion lay in the order of operations for reduce. In functional languages, the reduce function generally operates on a list in left-to-right order: apply a function to the first two element, take the result and pass it to the function and the third element, etc. So in a Lisp-like language, (reduce(1 2 3 4) -)is equivalent to(- 1 2 3 4)which is1 - 2 - 3 - 4 = -8in normal infix notation. In an APL-family language, expressions are evaluated right-to-left, so-/ 1 2 3 4is equivalent to(1 - (2 - (3 - 4))) = -2. My initial solution has two operators:1 solve 6is the number of steps to go from red to violet (5), andcur walk tocomputes the number of steps to go from a cumulative position to a given color. Once I played around with/and various operations in some REPLs, I realized I could justflipthe order of my input and the order of arguments towalk` to get the desired order of operations.

op part1 lines = solve parse@ 'r',lines[1]
op part2 lines = nums = parse@ 'r',lines[1]; solve nums[down (nums - 2) mod 7]
op from steps to = (((to - from) - 1) mod 6) + 1
op to walk cur = cur + (cur mod 6) steps to
op solve nums = (walk/ flip nums) - 1
op parse color = where color iota 'roygbv'

1

u/daggerdragon 5h ago

Psst: you missed a backtick (or too many backticks) somewhere around reduce so the formatting is all screwy. Fix please?

2

u/valhesh 5h ago edited 5h ago

[LANGUAGE: C++]

#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>



std::unordered_map<char, int> input_to_int {
    {'r', 0}, {'o', 1}, {'y', 2}, {'g', 3}, {'b', 4}, {'v', 5},
};


int move(int current_position, int input) {
    int distance_moved;


    if (input > current_position) {
        distance_moved = input - current_position;
    } else {
        distance_moved = (5 - current_position + 1) + input;
    } 


    return distance_moved;
}


int part1 (const std::vector<int>& input) {


    int current = 0;
    int total = 0;
    for (const int& in: input) {
        auto distance_moved = move(current, in);
        current = in;
        total += distance_moved;
    }
    return total;
}


int part2 (const std::vector<int>& input) {
    std::vector<int> input_quantity {};
    input_quantity.reserve(6);


    for (const auto& i: input) {
        input_quantity[i] ++;
    }
    int total = 0;
    int current = 0;
    auto remaining_inputs = input.size();
    while (remaining_inputs > 0) {
        
        int best_input = 0;
        int best_distance = -1;


        for (int candidate = 0; candidate <= 5; candidate ++) {
            if (input_quantity[candidate] > 0) {
                auto distance_moved = move(current, candidate);


                if (distance_moved > best_distance) {
                    best_distance = distance_moved;
                    best_input = candidate;
                }
            }
        }



        total += best_distance;
        current = best_input;
        input_quantity[best_input] --;
        remaining_inputs--;
    }



    return total;
}


std::vector<int> parse(const char * file_path) {
    std::ifstream in("input2.txt");
    char ch;
    std::vector<int> result{};


    while (in.get(ch)) {
        result.push_back(input_to_int[ch]);
    }


    return result;
}



int main (int argc, char ** argv) {
    
    std::vector<int> input_numbers = parse("input2.txt");
    int p1 = part1(input_numbers);
    int p2 = part2(input_numbers);


    std::printf("Part1: %d\n", p1);
    std::printf("Part2: %d\n", p2);


    return 0;
}

Feedback is appreciated, it's been a long time since I used C++ and I might do something stupid with the references.

EDIT: I just realized reading other solutions I overcomplicated part 2 and i might be an idiot :/

5

u/daggerdragon 4h ago

You are not an idiot! Even the best coders here have all done something stupid or ridiculously overcomplicated at one point or another. Facepalming at your own code is not a bad thing because it means you're learning, which is the entire point of this subreddit and Advent of Code as a whole :)

2

u/vubik 16h 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.

2

u/RustOnTheEdge 14h ago

I like it! I new there was a "simple" one liner to calculate the distance based on index positions, but I just couldn't get my brain to cook it up. So I ended up with this abomination:

for next_instruction in input.chars() {
    let new_pos = positions[&next_instruction];
    if new_pos == cur_pos {
        distance += 6;
        continue;
    }
    if new_pos < cur_pos {
        distance += 6 - cur_pos + new_pos;
    } else {
        distance += new_pos - cur_pos;
    }
    cur_pos = new_pos;
}
→ More replies (2)
→ More replies (1)

11

u/PandaParado 16h ago edited 16h 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)

8

u/oetam5002 16h ago edited 16h 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

8

u/Kooky_Ear_5662 11h 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).

→ More replies (10)

7

u/JustinHuPrime 18h 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.

7

u/Smylers 17h 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.

→ More replies (2)

6

u/POGtastic 18h ago edited 17h 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/Street-Apartment-512 11h 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

2

u/agorism1337 17h ago edited 17h ago

[LANGUAGE: NONE]

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

2

u/daggerdragon 4h ago

We need more than "I solved the puzzle with math ✌" from a top-level comment.

Explain your reasoning. Where did you get these magic numbers from? How did you count the number of letters in the input? You didn't even mention that this solution only works as long as there is at least one orange in the input.

Fully walk us through how you arrived at your solution including caveats.

→ More replies (3)

11

u/4HbQ 18h ago edited 14h 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 (12)

5

u/TallPeppermintMocha 18h 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/heijp06 17h ago edited 12h 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).

→ More replies (2)

5

u/ednl 13h ago edited 6h 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 (below) 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

→ More replies (8)

4

u/Gryphon-63 18h ago edited 17h 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 18h 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 17h ago edited 9h 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 17h ago

[Language: Uiua]

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

4

u/TumbleweedCold3542 17h 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)

4

u/sbt4 17h ago

[LANGUAGE: Uiua]

github

4

u/Aughlnal 16h ago edited 14h 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

→ More replies (8)

4

u/Fyver42 15h ago

[LANGUAGE: RISC-V Assembly]

Part 1 code

Part 2 code

4

u/lboshuizen 14h ago edited 10h 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)

4

u/Ok-Bus4754 14h ago edited 14h 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

4

u/p4bl0 13h 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

4

u/raevnos 12h 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)

4

u/RazarTuk 11h ago

[LANGUAGE: Perl... in the original Klingon]

paste


[Advent Games]

I mean... the language feels tailor-made for reverse code golf. Spelling out numbers in Klingon is an option, like how tev is initialized to pagh, not your filthy, sniveling, Terran symbol 0. I have this feature turned off after yesterday, where they answer was just too big to print in Terran symbols, but you can have it spell out numbers in Klingon, like giving maH jav instead of 16 for the first example in part 1. There isn't an else statement, so instead of saying if (var > 0) { ... } else { ... }, I have to say if (var > 0) { ... }; if (var == 0) { ... }. The syntax is mostly just RPN, but with everything spelled out in Klingon, like + being tIchel...

For example, take the line:

tevvaD tev jav b a tIchelHa' tIchel tIchel yInob!

"-vaD" is the Klingon grammatical suffix for datives, so it's being used here as an l-value marker. "jav" is the Klingon word for the number 6. "tIchel" is an imperative verb translating to "add them". "-Ha" is a suffix that acts sort of like Newspeak un-, so it's "un-add them" used here to mean "subtract them". And "yInob" is an imperative verb translating to "give it". So all together, it means "To the prize, prize six b a unadd-them add-them add-them give-it", which is an extremely verbose way of writing something like &tev tev 6 a b - + + <-, borrowing a C-inspired & to mark the first tev as an l-value.

(I just don't have anything interesting to highlight for the second runs or finals)

4

u/Single_Wrap1675 10h ago

[LANGUAGE: Uiua]

The trailing "\n" in the file gave me a headache.

Part 1, code golf style.

/+◫(+×6⊸=0 ◿6-) ⋉"roygbv" ⊂"r"

Part 1, "readable" (ha ha!)

# Letters to positions
Idx ← ⋉"roygbv"

# Travelled distance between 2 positions
Trav ← +×6⊸=0 ◿6-

# Total distance
Dist ← /+◫Trav Idx ⊂"r"

# Tests
˙⍤ =16 Dist "obbvb"
˙⍤ =11 Dist "roygbv"
˙⍤ =30 Dist "vbgyor"
˙⍤ =35 Dist "vvvvvv"

# Read from file
# The "↘₋₁" drops the ending "\n"
Dist ↘₋₁ &fras "2026aoc02.txt"

4

u/DullTicket5286 10h ago edited 10h 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)))

4

u/Daniikk1012 9h 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₂…

4

u/Future-Custard2288 8h ago edited 6h ago

[LANGUAGE: Chatter] Chatter is a toy language of my own invention, based on foggy memories of my first paid programming job in the long-dead language Hypertalk. If you're wondering why the list indexing statements have "+ 1" in them, it's because Chatter indexes lists from 1 and not 0.

Part 1

Part 2:

use get_input from "../util/io"

constant color_map is dictionary "r" to 0, "o" to 1, "y" to 2, "g" to 3, "b" to 4, "v" to 5

function map_colors_to_numbers takes string colors returns list of number is
    constant result is empty list of number
    repeat with i from 1 to length of colors
        append the value of character i of colors in color_map to result
    end repeat
    return result
end function 

function compute_distance_travelled takes list of number program returns number is
    constant remaining is list of 0, 0, 0, 0, 0, 0
    repeat with n in program
        add 1 to item n + 1 of remaining
    end repeat

    variable current_color is 0
    variable total_distance_travelled is 0
    repeat length of program times
        repeat with offset from 0 to 5
            constant next_color is (current_color - offset) mod 6 
            if item next_color + 1 of remaining is at least 1
                add 6 - offset to total_distance_travelled
                change current_color to next_color
                subtract 1 from item next_color + 1 of remaining
                exit repeat
            end if
        end repeat
    end repeat 
    return total_distance_travelled
end function

get_input
map_colors_to_numbers item 1 of it
compute_distance_travelled it

say "ANSWER:", it

4

u/Lord_Of_Millipedes 7h ago edited 7h ago

[LANGUAGE: C++]

Using aoc to learn more c++, the people with advanced templates and constexpr scare me but im happy with how this turned out

static inline int lut(char c) {
    switch (c) {
        case 'r': return 1;
        case 'o': return 2;
        case 'y': return 3;
        case 'g': return 4;
        case 'b': return 5;
        case 'v': return 6;
        default: return 0;
    }
}
char rev_lut[6] = {'r', 'o', 'y', 'g', 'b', 'v'};

uint64_t solve_p1(std::istream& in) {
    char ch;
    uint64_t total = 0;
    int start = 1;
    while (in >> std::noskipws >> ch) {
        int end = lut(ch);
        if (end == 0) continue;
        int move = end - start;
        if(move <= 0) move += 6;

        total += move;
        start = end;
    }

    return total;
}

uint64_t solve_p2(std::istream& in) {
    int freq[6] = {0};
    std::string seq = "";

    char ch;
    while (in >> std::noskipws >> ch) {
        int idx = lut(ch);
        if (idx == 0) continue;

        freq[idx -1]++;
    }

    for(int i=0; i<6; i++){
        int idx = (6 - i) % 6;

        if(freq[idx] == 0) continue;
        seq.append(freq[idx], rev_lut[idx]);
    }

    std::istringstream iss(seq);
    return solve_p1(iss);
}

1

u/encse 17h 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

1

u/daggerdragon 4h ago

Psst: you misspelled "language" which is why AutoModerator grinched at you 😅

→ More replies (1)

1

u/TreeSquirrles 15h ago

1

u/daggerdragon 5h ago edited 4h ago

Your Markdown is being escaped by the fancypants editor, so edit your comment and fix that wall-'o-link, please.

1

u/Lispwizard 15h ago edited 50m ago

[LANGUAGE: Lisp]

Actually in emacs lisp but making heavy use of the cl common lisp compatibility package (and sadly too long to fit here).

The two parts are separate functions instead of my usual one function with &optional part2 argument

topaz paste

1

u/daggerdragon 5h ago edited 4h ago

Please put that wall-'o-link behind some Markdown.

1

u/PM_ME_UR__RECIPES 13h ago

Here's my day 2 in JS

https://github.com/angusmglfraser/aoc-2026/blob/main/day2/index.js

I liked the satisfying little "aha" moment of realizing I didn't need to actually do the whole traversal for part 2

1

u/daggerdragon 5h ago

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

→ More replies (4)

1

u/dantose 7h ago edited 5h ago

[language: Powershell]

I decided to just convert everything into positions so I can just do math.

Part 1:

$replacements = @{
r = 0
o = 1
y = 2
g = 3
b = 4
v = 5
}
$instructions = gc input.txt; $replacements.Keys |% {$instructions = $instructions -replace $_, $replacements[$_]}
$move=0; $current = 0; $instructions -split ''|?{$_ -ne ''} |%{$Next = $_; $move= $move+(($next-$current+5)%6) +1; $current = $next}; $move

Part 2:

$move=0; $current = 0; $instructions -replace '0','6' -split ''|?{$_ -ne ''} |sort -Descending |%{$Next = $_; $move= $move+(($next-$current+5)%6) +1; $current = $next}; $move

1

u/daggerdragon 5h ago

Your code is not formatted at all. 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/e_blake 4h ago edited 3h ago

[LANGUAGE: mfour] [Advent Games]

  • [backwards] golf
  • ...many word do trick

I'm grokking that as "using words, not digits, is good". My mfour solution swaps in words for all digits, and avoids fifthglyph.

  • Int'l Toboggan Championships

That calls for fun quotation! A partial look at my solution:

macro(🛷data❄, translit(swallow(body(🛷input❄)), 🛷roygbv❄
  , nil🛷❄incr(random)random🛷❄incr(two)two🛷❄unit))
macro(🛷_do❄)macro(🛷do❄, 🛷macro(❄wrap(h$two)🛷, ❄wrap($two🛷,❄)🛷)❄
  +six-(six+$two-$unit)%six $incr(two)$nil🛷($❄two🛷,❄)
macro(🛷parta❄, math(do(nil, first(patsubst(data, 🛷.❄, 🛷)\&❄), 🛷_❄))))
macro(🛷partb❄, math(count(data)*six - first(first(body(🛷h❄incr(
  random))body(🛷h❄random)body(🛷h❄incr(two))body(🛷h❄two)body(
  🛷h❄unit)body(🛷h❄nil)))))

Run as:

m$(printf f|tr a-f /-:) -Dinput=daytwo.input daytwo.mfour

1

u/daggerdragon 4h ago

I didn't even get to the /r/Avoid5 prompt this year yet and you're already ahead of the curve 🤣

→ More replies (1)

1

u/Latter-Negotiation33 4h ago edited 4h ago

[LANGUAGE: Odin]

Link

1

u/daggerdragon 4h ago edited 4h ago

Put that wall-'o-link behind some Markdown, please. edit: 👍

→ More replies (1)

6

u/jonathan_paulson 18h ago

[LANGUAGE: Python]

Code. Video.

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

3

u/Boojum 18h 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.)

→ More replies (2)

3

u/NullT3rminated 18h 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 18h 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 18h ago edited 18h 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 18h 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 18h 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 18h ago edited 11h 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 18h ago edited 16h 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/yieldtoben 17h ago edited 17h 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

3

u/siener 17h ago edited 17h 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 17h 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/AndydeCleyre 17h ago

[LANGUAGE: Factor]

on GitHub

3

u/maneatingape 16h ago edited 11h 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.

→ More replies (4)

3

u/cinsolia 16h 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))

3

u/AMathMonkey 16h 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 (1)

3

u/voidhawk42 16h ago edited 15h ago

[Language: Dyalog APL]

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

3

u/mpsandiford 16h 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

3

u/PhysPhD 15h 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)
→ More replies (3)

3

u/Ghost-Engineer69 15h ago edited 7h 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);
    // this is a 1's based mod.  [1..6] is result. the % is
    // eliminated. the [fi]==[ti] branch eliminated. 
    uint8_t steps1Based = 6 - roygbiv[fi] + roygbiv[ti];
    return (steps1Based <= 6) ? steps1Based : steps1Based - 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 : string_view{"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;
}

After changes to the steps method (to remove the [ri]==[ti] condition and the % operation), execution time dropped to ~.9us. I do not think I can improve this any more.

→ More replies (1)

3

u/gisikw 15h ago edited 15h 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 😂

3

u/Outrageous72 15h 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])]));
}
→ More replies (2)

3

u/anaseto 15h ago edited 15h 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

3

u/No-House-866 15h ago edited 14h 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)

3

u/janek37 14h 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)

3

u/JWinslow23 14h 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)
→ More replies (2)

3

u/-beleon 14h 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

3

u/leftfish123 13h ago

[Language: Python]: here

Thought about itertools.cycle, decided to dust off my modulo thinking instead (turned out to be harder than I thought and I ended up getting my first star without % and added it only later). The second part was a matter of sorting. The PATTERN dictionary is probably an overkill, but I felt that O(1) lookup would be neater than O(n) with str.index().

3

u/muthm59 13h ago edited 12h 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
→ More replies (1)

3

u/andrewsredditstuff 13h ago edited 13h 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.

3

u/KindComrade 12h ago

[LANGUAGE: C#]

At first, I solved it using a straightforward approach, but then I looked more closely at the data and realized that we don't need to calculate the distance between all the points. We just need to count how many times we go through the cycle. And for part 2, the answer only depends on which colors are in the input.

+--------+-------+-------+-------+-------+--------+-------+-------+--------+
|        |  ITER |   P90 |   P95 |   P99 | STDDEV | RATIO |  MEAN | MEDIAN |
+--------+-------+-------+-------+-------+--------+-------+-------+--------+
| Init   | 10000 | 0.033 | 0.034 | 0.038 |  0.001 | 0.033 | 0.031 |  0.031 |
| Part 1 | 10000 | 0.004 | 0.004 | 0.006 |  0.000 | 0.049 | 0.003 |  0.003 |
| Part 2 | 10000 | 0.000 | 0.000 | 0.000 |  0.000 |       | 0.000 |  0.000 |
| Total  |       |       |       |       |        |       | 0.034 |  0.034 |
+--------+-------+-------+-------+-------+--------+-------+-------+--------+

Solution: Github

3

u/Downtown_Tone1879 12h 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)

3

u/DontRelyOnNooneElse 12h 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));
        }
    }

}

3

u/WolfRushHour 12h ago edited 17m ago

[LANGUAGE: Julia]

    program = replace(collect("r"*readline("input.txt")), (collect("roygbv").=>0:5)...)
    
    function distance(program)
        deltas = diff(program)
        sum(6*(deltas.<(1)) + deltas)
    end
    
    ans1, ans2 = distance(program), distance(-sort(program))

EDIT: remarks on the approach

The main idea is to use Julia's built-in diff() function on the Vector{Int} of states (waypoints) to get the distance of each step in the robot's program. At first we add the starting state "r" in front of the states from the input. We convert that to an array of Integers from 0 to 5 to generate our program.

Then, stepping inside the distance-function, diff of that array calculates the signed difference between two adjacent elements from left to right, which gets us an array of differences called deltas here. If an element of deltas is positive this is exactly the distance we go in that step. If the difference is 0, for example when going from state 3 to state 3, we want to go the maximum distance of 6 instead. If the difference is negative, e.g. -2, e.g. when going from state 3 to state 1, we cross a 0 and therefore have to go a distance of 4 instead. In each of those cases we needed to add a distance of 6 to that difference (to 0 and to -2 respectively, in this example). deltas.<(1) creates an array of type BitVector of the same length as deltas to indicate where such "overshooting" happens. Multiplied by 6 gives an array of the same length as deltas but with a 6 for the <(1) condition met and a 0 otherwise. That array is added to the signed differences in deltas. We sum up the resulting distances of all those steps.

For part 2 we sort the program-array first to create as many 0-steps as possible for a maximum of 6-distances. Additionally, we also want to get as many "overshoots" as possible, which means we sort in reverse order (instead of going from state 2 to state 3 we want to go from 3 to 2). We can use reverse(sort(program)) or sort(program, rev=true) for that. But because we're going to take differences later on anyway this is equivalent to multiplying sort(program) by -1. The whole approach certainly is not the fastest. But it is fast enough for this problem and I like the short but still readable code and the functional style!

→ More replies (3)

3

u/erikade 9h ago edited 4h ago

[LANGUAGE: Go]

Today's solution is really cute (20+ LoC) and runs accordingly (550ns 520ns mbairM4/24GB).

https://github.com/erik-adelbert/aoc/blob/main/2026/2/aoc2.go

Writeup is in the 2026/README

Happy coding everyone!

→ More replies (2)

3

u/Parzival_Perce 7h ago

[LANGUAGE: Python]

from itertools import pairwise

with open('d2.txt') as input:
    puzzle_input: str = input.readline().strip()

positions: dict[str, int] = dict(zip('roygbv', range(6)))


def find_distance(instructions: list[str]) -> int:
    instructions.insert(0, 'r')

    return sum(
        (positions[y] - positions[x]) % 6 or 6 for x, y in pairwise(instructions)
    )


def part1() -> int:
    return find_distance(list(puzzle_input))


def part2() -> int:
    return find_distance(
        sorted(puzzle_input, key=lambda x: positions[x] or 6, reverse=True)
    )


print(part1(), part2())

I'm not a huge fan of the need to write or 6 but whatever ill take it

→ More replies (1)

3

u/daic0r 7h ago

[LANGUAGE: Elixir]

Solution

3

u/tymscar 6h ago

[LANGUAGE: RACKET]

Day 2 of racket! Super fun but I'm way slower at this because I spend like an hour reading the docs, and figuring or dr racket. But that's what I signed up for and I love it.

The main trick today for part 1 was to treat its value as a number, but always treat it as 6 bigger and then mod 6 it. That way you don't have to do any crazy logic when you are passed the box you need to go to, because every box is still in front of you.

I found it crazy in racket that you have this idea of a #:result in a fold so you can use any number of accumulators you want but only export one at the end. Where was this all my life??

The big trick for part 2 is to realise you can use part 1 on a modified input, and the input is always modified in the same way. You always go RVBGYO and you repeat each one of those as many times as they show up in the original input.

Part 1 and Part 2

3

u/Honest-Positive-3273 5h ago edited 3h ago

[LANGUAGE: Python]

with open("route.txt", encoding="utf=8") as route:
    text = route.read()

counter = 0

for a, b in zip(text, text[1:]):
    step = a + b
    if step in {"ro", "vr", "oy", "yg"}:
        counter += 1
    elif step in {"ry", "og", "gv", "vo"}:
        counter += 2
    elif step in {"rg", "gr", "yv","vy"}:
        counter += 3
    elif step in {"yr", "ov", "vg", "go"}:
        counter += 4
    elif step in {"or", "rv", "yo", "gy"}:
        counter += 5
    elif step in {"rr", "oo", "yy", "gg", "vv"}:
        counter += 6
print(counter)
#print(text)

sorted = ""
for c in text:
    if c == "r":
        sorted += "r"

for d in text:
    if d == "v":
        sorted += "v"

for e in text:
    if e == "b":
        sorted += "b"

for f in text:
    if f == "g":
        sorted += "g"

for g in text:
    if g == "y":
        sorted += "y"

for h in text:
    if h == "o":
        sorted += "o"

#print(sorted)

counter2 = 0

for x, y in zip(sorted, sorted[1:]):
    step2 = x + y
    if step2 in {"ro", "vr", "oy", "yg"}:
        counter2 += 1
    elif step2 in {"ry", "og", "gv", "vo"}:
        counter2 += 2
    elif step2 in {"rg", "gr", "yv","vy"}:
        counter2 += 3
    elif step2 in {"yr", "ov", "vg", "go"}:
        counter2 += 4
    elif step2 in {"or", "rv", "yo", "gy"}:
        counter2 += 5
    elif step2 in {"rr", "oo", "yy", "gg", "vv"}:
        counter2 += 6
print(counter2)

2nd day trying to learn coding from zero knowledge. This is what I came up with. Copared to the other python solutions here (which also don't understand) it feels like pulled out a calculator and calculated everything by hand. I thought it might be funny for experienced people to look at ^

→ More replies (1)

3

u/cbooth 4h ago

[LANGUAGE: COBOL] How screwed am I trying to do all this in COBOL?

paste

3

u/EasyObjective360 3h ago

[LANGUAGE: Python]

85 bytes solution for day 2 part 2

v=[i for i in map("rvbgyo".find,open("input.txt").read())if~i];print(6*len(v)-max(v))
→ More replies (1)

1

u/yoni-kosiner 18h 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
→ More replies (2)

1

u/mknoll1 18h ago edited 18h 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 18h ago edited 17h 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 18h ago

[LANGUAGE: Python]

github

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

2

u/hugh_tc 18h ago edited 18h ago

[LANGUAGE: Python 3]

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

paste, eta: cleaned-up

→ More replies (5)

2

u/apersonhithere 18h ago

[LANGUAGE: Python]

came up with an elegant solution today, i think

p1; p2 is nearly the same

2

u/1234abcdcba4321 18h 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 18h ago edited 11h 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 18h 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 18h 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 18h 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 18h 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 18h 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 18h ago

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

paste

2

u/xoronth 18h 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 18h 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 18h ago edited 18h 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 18h 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

→ More replies (3)

2

u/UseUnlucky3830 18h ago

[LANGUAGE: Julia]

Maybe not the best solution, but it works.

GitHub

2

u/agorism1337 18h ago edited 17h ago

[LANGUAGE: AWK]

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

2

u/ynadji 18h ago edited 18h 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 18h 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 18h 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__ 18h 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 18h ago edited 17h 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 18h ago

[LANGUAGE: Scala]

code

2

u/snubian 17h ago edited 17h 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 (3)

2

u/throwaway6560192 17h 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 17h 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 17h ago edited 10h ago

[Language: Crystal]

Code

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

2

u/acquitelol 17h ago edited 15h 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 17h ago edited 17h 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 17h 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/Dense-Virus-1692 17h 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

2

u/mstksg 17h 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/kbielefe 17h 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.

2

u/Jdup1n 17h 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)

2

u/YenyaKas 17h 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.

2

u/terje_wiig_mathisen 17h 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;

2

u/Godlyflame 17h 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)

2

u/ColonialDagger 17h 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)

2

u/jgage 17h 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;
}

2

u/KyxeMusic 17h 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

2

u/tqzd 16h 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
))))

2

u/azzal07 16h 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.

2

u/WesternNicator 16h ago edited 16h 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

2

u/SpaceHonk 16h ago

[LANGUAGE: Swift]

code

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

2

u/MidnightLoud2032 16h ago

[LANGUAGE: Java]

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

2

u/Secret_Caramel2095 16h 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)

2

u/mosredna101 16h 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);
}

2

u/Fuzzy_Patterns 16h 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

2

u/CEOnism 16h ago edited 8h 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);

2

u/flwyd 16h 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]]
}

2

u/ArmadilloSuch411 16h 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}")

2

u/aknusmag 16h 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

→ More replies (2)

2

u/xoronth 16h ago edited 16h 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 ⟩

2

u/p88h 16h 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%)

2

u/r_so9 16h ago edited 13h ago

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

paste

2

u/Sudowiec 15h 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()

2

u/DelightfulCodeWeasel 15h 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

→ More replies (5)

2

u/ADifferentRealm 15h 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));

2

u/dijotal 15h 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

2

u/Sam_Ch_7 15h 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)))
}

2

u/Daniel_Rybe 15h ago edited 15h 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.

→ More replies (1)

2

u/ray10k 14h 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

2

u/shmoodla 14h 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)));

2

u/TCH69 14h 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;
}

2

u/Lindi-CSO 14h ago

[LANGUAGE: C#]

Lovely little puzzle. Part 1 was pretty much just do as the instructions say and for part 2 I could reuse all of part 1 since I coded a bit more clean.

That's definetly the challenge this year for me, Clean Code all the way.

Part 1 & 2

2

u/According_Offer_2483 14h ago edited 14h ago

[LANGUAGE: Python]

113 byte solution for day 2 part 1

p,s=0,"roygbv"
_,dist,_=zip(*[(k:=s.find(c),(k-p-1)%6+1,p:=k) for c in open("2").read()[:-1]])
print(sum(dist))

2

u/SymmetryManagement 14h 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

2

u/sauntcartas 14h ago edited 8h 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);

2

u/Bramdevriez 14h 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)

2

u/Boris01100000 14h 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!

2

u/Thomasjevskij 14h 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

2

u/friedkeenan 14h 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.

2

u/Slow-Assistance-4303 14h 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

2

u/Falcon731 14h 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")
}

2

u/ash30342 14h ago

[LANGUAGE: Java]

Day 2

Both parts run in < 1ms.

Part 1 required a bit of thinking with regards to calculating the distance. Part 2 was actually easier to me, just using Java's sort method with a custom order.

2

u/Royal_Pin_1971 14h ago edited 13h ago

[LANGUAGE: PFCL]

dist = \(p, t). int.add(int.mod_euclid(int.subtract(int.subtract(t, p), 1), 6), 1)

part1 = \(cs).
  let st = list.fold_left(\(acc, t). {pos: t, total: int.add(acc.total, dist(acc.pos, t))},
                          {pos: 0, total: 0}, cs) in
  st.total

greedy_move = \(st).
  match list.find(\(k). int.greater_than(list.get(0, int.mod_euclid(int.subtract(st.pos, k), 6), st.counts), 0),
                  list.range(0, 6)) with
  | Just(k) ->
      let q = int.mod_euclid(int.subtract(st.pos, k), 6) in
      {pos: q, total: int.add(st.total, int.subtract(6, k)),
       counts: list.set(q, int.subtract(list.get(0, q, st.counts), 1), st.counts)}
  | Nothing -> st

2

u/olamberti 13h ago edited 8h ago

[LANGUAGE: Python]

I created a function that calculates the distance between two colors based on modulo arithmetic.

Part 1: just loop through the input and calculate the distance traveled.

Part 2: a lot of solutions used some sort of general sorting which only holds for certain inputs. I checked my input with a counter and noticed 'y' is missing, so I tried to figure out a different method (I had the wrong intuition about the sorting method that it should not work). This is what I came up with:

  1. Create a color counter for the input.
  2. Jump on the current color as many times we can and zero out its counter.
  3. Look for the next color with non-zero counter, based on sorting with the distance function as the key.

Repeat the above steps until we all counters are zero.

Part 2 (new): I noticed in my counting algorithm there are two cases basically: either we jump to the same color where we are, which is a 6 distance step, or we switch to an other color, which is less. Based on this we can define the P2 answer as 6 * len(input) - losses. The second observation is that these losses happen due to color switches, and the final loss is only depending on the "closest" color to "r", not on the way how we got there. So we just need to check the input and look for the "least" efficient jump.

pattern, program = "roygbv", open("d02.txt").read().strip()
dist = lambda a, b: 6 - (pattern.index(a) - pattern.index(b)) % 6

print(sum(dist(a, b) for a, b in zip("r" + program, program)))
print(6 * len(program) - max((-pattern.index(c)) % 6 for c in set(program)))
→ More replies (2)

2

u/1AlanM 13h ago

[LANGUAGE: Python]

https://github.com/MrMorrison-CS/AoC2026/blob/main/day2.py

Part 1 was pretty straightforward. measured the distance between the characters as I looped through the program

Part 2 counted the occurrence of each letter (other than the first occurrence of each letter you're adding 6 to the distance each time)

2

u/chkas 13h ago

[LANGUAGE: Easylang]

Solution

2

u/TheScown 13h ago

[LANGUAGE: Scala]

Link

2

u/FlockOnFire 13h ago

[LANGUAGE: Gleam]

Using this year to learn a new language. Used F#, Lisp and Elixir previously, loving Gleam so far as well!

https://raw.githubusercontent.com/janssen-io/AdventOfCode/refs/heads/main/2026/aoc_gleam/src/day_02.gleam

2

u/Freecelebritypics 13h ago

[LANGUAGE: Rust]

fn counts(s: &[u8]) -> [usize; 6] {
    let mut a = [0; 6];
    for ch in s {
        let i = match ch {
            b'r' => 0,
            b'o' => 1,
            b'y' => 2,
            b'g' => 3,
            b'b' => 4,
            b'v' => 5,
            _ => continue,
        };
        a[i] += 1;
    }
    a
}

fn next_max_step(a: &[usize], i: usize) -> Option<(usize, usize)> {
    if let Some(j) = a[..=i].iter().rposition(|x| *x != 0) {
        Some((j, (a.len() - i) + j))
    } else if let Some(j) = a[(i + 1)..].iter().rposition(|x| *x != 0) {
        Some((i + j + 1, j + 1))
    } else {
        None
    }
}

pub fn part_two(s: &[u8]) -> usize {
    let mut a = counts(s);
    let mut dist = 0;
    let mut i = 0;
    while let Some((j, step)) = next_max_step(&a, i) {
        dist += step + (a[j] - 1) * a.len();
        a[j] = 0;
        i = j;
    }
    dist
}

Every day I'm counting characters

2

u/Bigbudddo 13h ago

[LANGUAGE: C#]

Probably a much more elegant solution than this but threw this together pretty quickly and it spit out the correct answer.

Task<int> SolvePartA(string puzzleA) {
    var steps = 0;
    var currentPosition = 'r';
    var positionIndexer = new Dictionary<char, int>() {
        { 'r', 0 }, 
        { 'o', 1 },
        { 'y', 2 },
        { 'g', 3 },
        { 'b', 4 },
        { 'v', 5 },
    };
    
    var instructionSet = puzzleA.ToCharArray();
    foreach (var instruction in instructionSet) {
        var currentIndex = positionIndexer[currentPosition];
        var toIndex = positionIndexer[instruction];
        var stepsToReach = currentIndex == toIndex 
            ? positionIndexer.Count 
            : (toIndex - currentIndex) < 0
                ? positionIndexer.Count + (toIndex - currentIndex)
                : toIndex - currentIndex;
        
        steps += stepsToReach;
        currentPosition = instruction;
    }
    
    return Task.FromResult(steps);
}

Task<int> SolvePartB(string puzzleB) {
    var weightings = new Dictionary<char, int>() {
        { 'r', 6 }, 
        { 'o', 1 },
        { 'y', 2 },
        { 'g', 3 },
        { 'b', 4 },
        { 'v', 5 },
    };

    var decomp = puzzleB
        .ToCharArray()
        .GroupBy(c => c)
        .OrderByDescending(grp => weightings[grp.Key])
        .Select(x => new { Key = x.Key, Count = x.Count() })
        .ToList();

    var sb = new StringBuilder();
    foreach (var position in decomp) {
        for (var i = 0; i < position.Count; i++) {
            sb.Append(position.Key);
        }
    }
    
    return SolvePartA(sb.ToString()); 
}

2

u/hextree 13h ago edited 12h ago

[LANGUAGE: Python]

Code

Video

Most of the logic relies on a circular distance function that avoids iterations, part 2 makes use of the Python collections Counter.

2

u/SodaDrunkenski 12h ago

[LANGUAGE: Python]

Solution

My answer is basically the same as others I've already seen in this thread, just formatted slightly differently I suppose and likely less efficient. Looking forward to seeing everyone else's code!

2

u/omnster 12h ago

[LANGUAGE: Wolfram Mathematica]

The solution with some comments to explain the logic

input = Import[ NotebookDirectory[]<>"/input/input_02.txt", "Text"]//Characters

(* The possible characters *)
chars = Characters@"roygbv"

(* Part 1 *)
(* Assign a number to each character *)
pos = AssociationThread[ chars -> Range[6]];

(* Compute the steps taken by moving between characters *)
p1steps[a_, b_] := Mod[ pos[b] - pos[a], 6 , 1];

(* Keep the state as  {current char, distance walked} *)
(* Each step replaces current char with the char from instruction and adds steps walked *)
(* Initial state is {"r", 0 } *)
init = {"r", 0} ;

(* One step for part 1 *)
p1[ { char_ , distance_ }, instruction_ ] := { instruction , distance + p1steps[ char, instruction]}

part1[ sequence_ ] := Last@Fold[ p1 , { "r", 0}, sequence];

part1@input

(* Part 2 *)
(* The logic is apparently to sort the input in an appropriate way, then
feed the sorted input to part1*)

(* Find the chars present in the input *)
ourChars = Union@input // SortBy[  pos ]

(* One candidate for the optimal order of the input is apparently such that first go all r's then go all the letters that are second best for r, then go all the letters that are the second best for the second best for "r". *)

(* Importantly, "the second bests" should be chosen from only ourChars. *)

(* The long run of the last letter will all give longest jumps regardless of the letter *)

(* Now we want to process ourChars to find the proper order. *)

(* This function finds the second best from the remaining chars *)
secondBest[ letter_, chars_] := First@TakeLargestBy[ DeleteCases[ chars , letter], p1steps[letter, #]&, 1]

(* Let's keep the state as {sorted, unsorted} *)
(* Then at each step *)
sortSecondBestStep[  {sorted_, unsorted_ }] :=
Module[ { sb = secondBest[ Last@sorted, unsorted]},
{ Join[ sorted, { sb}], DeleteCases[ unsorted, sb] }]

(* Nest the sorting function the required number of times, then keep only the first element (sorted) *)
p2order= First@Nest[ sortSecondBestStep, {{"r"}, DeleteCases[ourChars, "r"] }, Length@ourChars-1]

2

u/iiMqx 12h ago

[LANGUAGE: Python]
Trying to see what ive learnt from my first year at uni programming, feedback appreciated :3
https://github.com/AspxctQX/AdventOfCode26/blob/main/Day2/day2.py

→ More replies (1)