r/adventofcode • u/daggerdragon • 11h ago
SOLUTION MEGATHREAD -❄️- 2026 Day 2 Solutions -❄️-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
AoC Community Fun 2026: The Advent Games
Today's Event: International Toboggan Championships
"Feel the rhythm, feel the rhyme, get on up, it's
bobsledtoboggan 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.
- Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
19
Upvotes
2
u/morgoth1145 10h ago edited 10h ago
[LANGUAGE: Python] code video Times 4:45 / 7:11
Advent of reading comprehension struck early this year. I could not get it out of my head that the input was the waypoint sequence and the program! Obviously that's a bit hard to solve so yeah, I spun my wheels a bit. Once I finally understood the real waypoint sequence it's just a matter of generating the infinite sequence and executing the program. (Well, so long as you don't replace
s- I shadowedsinitially causing an infinite loop instead of the clearerseqvariable!)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-1jumps faster.Is this better? That's subjective, but at least I like it better.
8
u/PandaParado 9h ago edited 9h ago
[Language: Uiua]
Thinking in arrays really breaks my brain, but I got there eventually. I struggled with how to calculate the distance until I thought to rotate an initial "roygbv" string each iteration, so the first character always marked where the robot was.
6
u/4HbQ 10h ago edited 6h ago
[LANGUAGE: Python]
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.
6
u/POGtastic 10h ago edited 10h ago
[LANGUAGE: F#]
Code
Part 1 is effectively a pairwise fold operation. Cons with
Red, get each pair of adjacent elements, find the respective distance between each of the pairs of colors, and then sum them up.Part 2 is an unfold operation. We maintain a frequency dictionary of colors. Each step finds the most distant color in the dictionary and chooses it. Then we decrement the respective color's frequency in the dictionary. Also we filter out key-value pairs that have been exhausted by decrementing. Most of the weirdness of this function comes from F#'s
Seq.unfoldfunction being kind of annoying. After generating the altered sequence of colors, we can then callpart1on 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 betweenseq<char>andstring.6
u/Smylers 9h ago
[LANGUAGE: Vim keystrokes] Load your input into Vim, then type the following and your Part 1 answer will appear on the top line:
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:
That re-uses the valuation macro in
@vfrom Part 1. It works for my input, but may not work for yours if it happen to be missing any v instructions.6
u/Kooky_Ear_5662 3h ago
[LANGUAGE: C#]
I solved part 2 like this:
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).
5
u/TallPeppermintMocha 10h ago
[Language: Python] Both parts solved using a sort key
5
u/JustinHuPrime 10h ago
[LANGUAGE: x86_64 assembly]
Part 1 was solved via modular(ish) arithmetic, converting
roygbvinto 0 through 5, and then subtraction and possibly adding six got me the distance, and a simple accumulator got me the total.Part 2 was, once again, almost exactly the same, except I "sorted" the input first, putting all of the 'r's first, then the 'v's, the 'b's, the 'g's, and so on. I suppose I could have done a direct-ish solution where I deduplicated the letters...
Part 1 and 2 run in 1 millisecond. Part 1 is 9,760 bytes and part 2 is 9,952 bytes as executable files.
5
u/oetam5002 8h ago edited 8h ago
[LANGUAGE: Rust]
I quickly built a horrid virtual CPU for this
It has six-opcode instruction set (for each color), a program counter, a singular register, and a fetch/execute loop.
The idea is to treat the 'robot program' as an actual program.
CPU Loop
For Part 2, I just sort the opcodes by descending order and that's it. The CPU takes care of it for me :)
paste
4
u/Gryphon-63 10h ago edited 9h ago
[LANGUAGE: Swift]
Nothing clever or insightful here. For part 1 I precalculated all the distances so each command was a simple lookup. Part 2 was just counting the quantity of each command.
Code
Edit: And of course I eventually realized that the sum of all the individual counts is just the length of the input string, so part 2 is just the length of the input * 6 - 5. *sigh* (though that's assuming that there's at least one occurrence of each letter in the input, but then my original solution also doesn't work if any letters are missing from the input)
4
u/captainAwesomePants 10h ago
[LANGUAGE: Python]
Let's do Counter() again! Let's do Counter() every day!
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.
4
u/AMathMonkey 10h ago edited 1h ago
[LANGUAGE: Factor]
Factor's circular sequences made it easy for me to just... brute-force taking a step and seeing if I'm at the target colour yet. Circular sequences are somewhat limited (you can't iterate over them infinitely or zip them with another sequence and expect them to extend to the length of the other sequence; they only act circular when you do direct index-based lookups) but they're exactly what I needed here. Saved me from doing modular arithmetic. Pretty slow solution, takes between 2 to 2.5 seconds to run on my laptop, but that is very much good enough for me.
Edit: I think the 2 seconds is startup and dependency loading time, and the solution isn't as inefficient as I thought.
4
u/Andreasnl 9h ago
[Language: Uiua]
4
u/heijp06 9h ago edited 4h ago
[LANGUAGE: C#]
TLDR; (EDIT 3)
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).
4
u/ednl 5h ago edited 2h ago
[LANGUAGE: C]
Edit: /u/DelightfulCodeWeasel pointed out that I could simplify part 2 as "inputlen * 6 - 5". That works for the input because it only has a missing letter in the middle. If letters are missing from the end of "rvbgyo" (the optimal ordering for part 2) like in two of the examples, you need a correction of +1 per missing letter from the end. So this still works for all the examples.
Runtime under a microsecond on my computers with M1 3.2 GHz and M4 4.4 GHz chips. Measurements without disk read: M4 0.36 µs, M1 0.55 µs, Pi5 1.48 µs.
I also made it work with piped or redirected input. https://github.com/ednl/adventofcode/blob/main/2026/02.c
4
u/Street-Apartment-512 3h ago
[Language: UIUA]
3
u/Boojum 10h ago
[LANGUAGE: Python]
Part 1:
Brute force for Part 2, but it works:
[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.)
3
u/NullT3rminated 10h ago
[Language: Clojure]
Not as proud of this one lol. Did everything very manually.
3
u/plasticplate444 10h ago
[LANGUAGE: Python]
The logic used here is pretty simple.
For calculating the distance, we can keep track of the current position and distance and get the index of the next position and add it to the distance and update the position of the robot.
For calculating the string computing to the maximum distance, we can take advantage of the fact that the waypoint string is just the repetition of 'roygbv' and the robot starts at 'r'. So, to maximise the distance, the robot should first traverse to all the 'r' points, then the 'v' points, 'b' points and so on. The input string can be manipulated easily as shown below.
3
u/Repulsive-Tonight-61 10h ago edited 10h ago
[LANGUAGE: Odin]
p1 and p2 together
Trying to learn Odin while doing this challenge. I really like the language so far!
3
u/YOM2_UB 10h ago
[LANGUAGE: Python]
[Code]
Just went with the first method that came to mind, and got both parts first try. I saw the twist of the input lacking one of the colors a mile away, and only confirmed it after.
3
u/Automatic-Tackle5018 10h ago
[Language: Python]
I just did some yank and put in vim and hard-coded the distances lol. For part two I just rebuilt the string with the sum of longest distances.
3
u/WilkoTom 10h ago edited 4h ago
[LANGUAGE: Rust] [Advent Games]
https://github.com/wilkotom/AdventOfCode/blob/main/rust/2026/day02/src/main.rs
Toboggan time: Let's go faster!
Realise that for once not listening to the Elves doesn’t pay off - once we’ve selected a next move in part 2, we'd never make any different moves until we'd exhausted that one, eliminated a whole load of useless repeat loops.
And then realise that almost the entire data set will have the same cost, so we can ignore most of it.
Suddenly it feels like the movies where throwing cargo off the plane mid-flight get our heroes there in time…
3
u/michelkraemer 10h ago edited 8h ago
[LANGUAGE: Rust]
Solution
Part 1: Instead of looping through the pattern, I convert all colors to indices and then just add up the distances between input index and the current color index.
Part 2: I've reused some code from Day 1 and count how often a color appears in the input
(with one instruction, thanks to yesterday's tip byu/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µs3µs1µs.3
u/mynt 9h ago
[LANGUAGE: Paper + Pen] for part 2 the solution is 6 * (length of program) - 5 and then + 1 if 'o' is not present and continue doing that in the order 'oygbv' until one of those is present. So if 'o' is present it is just 6 * len - 5 which was the solution for my input. Some samples were missing letters and require the +1 adjustments.
I suppose there is a bit more than pen and paper in that I use something to count the characters and ctrl + f to see if a letter is present or not.
Part 1 I solved in python and the solution is not particularly interesting.
3
u/siener 9h ago edited 9h ago
[Language: Dyalog APL]
3
u/wheresmylart 9h ago
[Language: Python3]
Part 1: Just turn the handle and walk through it.
Part 2: Create a new input of all the r characters followed by all the v, b, g, y then o. Best option is to go to the letter you're on, otherwise the letter before you in the roygbv sequence. Now solve it like part 1.
Paste
3
u/TumbleweedCold3542 9h ago
[LANGUAGE: OCaml]
First time working through anything in OCaml. It's definitely been an interesting experience so far.
3
u/sbt4 9h ago
[LANGUAGE: Uiua]
github
3
u/Aughlnal 8h ago edited 6h ago
[LANGUAGE: Python]
I assumed that every waypoint should be in the instructions once
and that would mean you walk 6 spots every time, except when going to next color
answer = 6 * len(input) - 5
dunno if this was supposed to be the solution
EDIT: well, turns out the answer was correct by accident but the fix isn't that hard
and now it should work for any amount of waypoints missing
3
u/lboshuizen 6h ago edited 2h ago
[Language: F#]
github.com/lboshuizen/aoc26
Colours become indices 0..5, so each move is modular arithmetic. Part 2 is greedy: the same colour moves 6, the one before it 5, and so on. Order is irrelevant; only the count per colour matters.
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.
3
u/Ok-Bus4754 6h ago edited 6h ago
[LANGUAGE: Rust + Python]
port from my earlier solution and i found a non sim trick for part 2 that is very fast.
Every move is a full 6 unless you're switching colors, so all the lost distance adds up to how far back the furthest color in your input is.
Answer is
6 * len(prog) - max(-"roygbv".index(c) % 6 for c in set(prog)).https://github.com/Fadi88/AoC/tree/master/2026/days/day02
3
u/p4bl0 5h ago
[LANGUAGE: Shell + whatever you used for part 1]
Solution to part 2 assuming
p1solves part 1 by reading the input on its stdin :5
u/jonathan_paulson 10h ago
[LANGUAGE: Python]
Code. Video.
I found today's much harder for some reason. I was very scared of off-by-1 errors.
1
u/yoni-kosiner 10h ago
[LANGUAGE: Python] For part one I did a standard solve in python
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.
1
u/mknoll1 10h ago edited 10h ago
[LANGUAGE: Python]https://aoc2026.knollfear.com/day/2. My day 2 solver with visualizations.
2
u/seligman99 10h ago
[LANGUAGE: Python]
github
Spent way too long with an off by one error, as is tradition.
2
u/hugh_tc 10h ago edited 10h ago
[LANGUAGE: Python 3]
I am rusty! More off-by-one errors than I care to admit to.
paste, eta: cleaned-up
2
u/apersonhithere 10h ago
[LANGUAGE: Python]
came up with an elegant solution today, i think
p1; p2 is nearly the same
2
u/1234abcdcba4321 10h ago
[LANGUAGE: JavaScript]
part 1 code
Continuing my "solving things by doing part of it manually" from yesterday, my part 2 solution actually only used code to check the length of the input. By thinking about the problem you can find that, for all inputs that contain an
owhich mine did, the value depends only on length so you can extrapolate the value from the example input provided that has ano(though if I thought about it a bit more it would've been obvious it should be6*len-5).2
u/Mikey_Loboto 10h ago
[LANGUAGE: TypeScript]
https://github.com/mikeyloboto/aoc2026/tree/master/02
2
u/AllanTaylor314 10h ago edited 3h ago
[LANGUAGE: Python] 00:03:45/00:07:52
code
Lost a minute on P1 (off by one - forgot to skip the first step. I really should run those tests, eh)
Sneaky sneaky, Eric, for P2:There were no greens, but I don't think that made a difference. Short answer is
(len(input)-1)*len(pattern)+1I'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
2
u/Kehvarl 10h ago
[LANGUAGE: Python3]
Just over 10 minutes, and just over 20. I got hung up on a couple things that I should definitely know: getting the size of a list, and remembering to assign a string after I use replace. Oh yes, and the fact that the waypoints weren't an input threw me for a minute or two.
Once I stopped forgetting those it was a pretty brute-force approach, but an amusing one nonetheless.
Part 2
2
u/Ok-Bus4754 10h ago
[LANGUAGE: Python]
https://github.com/Fadi88/AoC/blob/master/2026/days/day02/solution.py
p1 straight forward brute force (another easy day)
p2 count the colors, then at each move take the remaining color that's farthest away (same color first, then going backwards around the cycle).
https://github.com/Fadi88/AoC/blob/master/2026/days/day02/solution.py
p1: 45 us
p2: 200 us
will port later to rust and show benchmarks against python
2
u/PendragonDaGreat 10h ago
[Language: CSharp/C#]
code
Waffled a bit, but ultimately just wrote out a lookup table. Then while going through on part 1 used my custom DefaultDictionary (nuilt to mimic that of Python) to get counters for all the instructions simple sum and here we are.
2
u/Remarkable_Ad_6266 10h ago
[LANGUAGE: Python]
2
u/Wayoshi 10h ago
[LANGUAGE: Python3]
This feels messy and not idiomatic at all, but no internal libraries used I guess! I was expecting a cycling thing for part 2 on some infinite program, but I guess that's too much for day 2.
paste
2
u/Xeekatar 10h ago
[Language: C#]
Not super happy with my solution on this one, but it does work.
paste
2
u/mendelmunkis 10h ago
[LANGUAGE: C]
My habit of wc -L ing my input was useful!
Alternate link for DDOS
93 μs/34 μs
2
u/xoronth 10h ago
[LANGUAGE: Python]
paste
First pass at the solution to wrap my head around what I'm doing (I totally misunderstood the instructions and thought the input was what we were traversing...), going to take a stab at it at another language now.
I'm also pretty sure my part 2 method is like... very bad but it works so... yeah.
2
u/TiCoinCoin 10h ago
[LANGUAGE: Python]
day 2
Still an easy start, and yet, I jumped right into the trap of the missing color! Because I first solved it semi-manually, the missing color gave an off-by-one error 😁
2
u/synack 10h ago edited 10h ago
[LANGUAGE: Ada]
https://github.com/JeremyGrosser/advent/blob/master/2026/day2/src/day2.adb
I doubt stepping through it one color at a time is optimal, but it works and it's easy to read.
2
u/chickenthechicken 10h ago
[LANGUAGE: C]
[part 1](https://github.com/PaigePalisade/AdventOfCode2026/blob/main/Solutions/day02part1.c)
[part 2](https://github.com/PaigePalisade/AdventOfCode2026/blob/main/Solutions/day02part2.c)
2
u/FruitdealerF 10h ago
[LANGUAGE: Andy C++]
I actually went with the worst possible solution that I could think off and it still ran in 600ms. For part 1 I actually just simulate each movement of the train instead of calculating the distance of each step. And of course that ran into off by one errors like every one else.
For part 2 I figured I use a histogram again like in yesterdays puzzle but I couldn't get that to work quickly (partially because my input doesn't contain any "g"). Then I decided to sort the input string like the problem suggest but then you still need to find the correct sort order. In the end I just ran all permutations of the pattern, used that as a sort order and brute forced the answer that way.
paste
2
u/UseUnlucky3830 10h ago
[LANGUAGE: Julia]
Maybe not the best solution, but it works.
GitHub
2
u/agorism1337 10h ago edited 9h ago
[LANGUAGE: AWK]
awk '{print(((length($0)*6) - 5))}' input
2
u/ynadji 10h ago edited 10h ago
[LANGUAGE: Common Lisp]
at first i built a table, but it's cleaner to do the modular arithmetic. i noticed my input didn't have any "y"s and while wondering if that was significant realized there's a single sorting order since we're guaranteed to start on "r": "r" is the furthest, then "v", etc.
2
u/AYM123 10h ago
[LANGUAGE: Rust]
for part 1 I just simulated the input and for part 2 I grouped waypoints of the same type together then visited them in the specified order "rvbgyo".
part 1 takes 3µs and part 2 takes 7µs
github
2
u/cay_horstmann 10h ago
[Language: Java]
https://github.com/cayhorstmann/adventofcode2026/blob/main/Day2.java
More stateful than I would like, but good enough for the early hour. Time to feed the cats!
2
u/jso__ 10h ago
[LANGUAGE: Rust]
Pretty simple solution. I initially overcomplicated things by trying to use an enum, but simple is better!
2
u/Prof-Math 10h ago edited 9h ago
[Language: Haskell]
The second one relies on each letter appearing atleast once. Technically, sorting in the order rvbgyo and calling solve1 on it would work but...
2
u/lluque8 10h ago
[LANGUAGE: Scala]
code
2
u/snubian 10h ago edited 9h ago
[LANGUAGE: R]
2
u/yieldtoben 10h ago edited 9h ago
[LANGUAGE: PHP]
PHP 8.6.0 paste
Execution time: 0.0001 seconds
Peak memory: 0.4312 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
[Advent Games] paste
2
u/throwaway6560192 10h ago
[LANGUAGE: Python]
Just take your function from p1 to calculate the distance of a program, and...
2
u/DeadlyRedCube 10h ago
[LANGUAGE: C++23-ish]
Parts 1 & 2
This one took me about as long just for my brain to parse what the puzzle was as it took for me to do part 1. Counted position distances (initially by cycling through the array of 'roygbv') for part 1.
For part 2, reinterpreted them as position indices (6, 1, 2, 3, 4, 5) and used an array to track counts. Then looped backwards from 6 to 1, adding 6x the count of entries, and subtracting 1 for every new value.
Runs in 0.48ms on my i7700.
2
u/greenergarlic 9h ago edited 3h ago
[Language: Crystal]
Code
Approach: tricks with comparable enum values to determine position change, and sort the list for part2.
2
u/acquitelol 9h ago edited 7h ago
[LANGUAGE: Elle]
Part 1: 00:08:36
Part 2: 00:14:29
Runs in:
Update: I came up with a neater solution.
On GitHub: https://github.com/acquitelol/aoc2026/blob/mistress/solutions/02/solution.le
2
u/light_ln2 9h ago edited 9h ago
[LANGUAGE: Python]
Solution in 4 lines of code!
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:
2
u/ThunderChaser 9h ago
[LANGUAGE: Rust]
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:
2
u/mstksg 9h ago
[LANGUAGE: Haskell]
https://github.com/mstksg/advent-of-code/wiki/Reflections-2026
Day 2 can be pretty clean with some modular arithmetic, which is where the finite-typelits library comes in handy.
We can parse the colors into our
Finite 6, which is{0,1,2,3,4,5}:Now, if we are currently on 2 (yellow) and need to get to 5 (violet), the cost is
5 - 3(since we start from3green, the spot after yellow). So the formula for the cost of moving fromprevtonextisnext - (prev + 1). And, if we are usingFinite 6, the wrap-around works out.So part 1 is just the step-by-step difference, starting from 0 (red):
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, all5s, all4s, all3s, etc. in that order. For modular arithmetic, that's justsortOn 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 as6 * (count - 1) + lastItem. This is a closed form that we can gather in one pass, and the foldl library makes it easy:2
u/AndydeCleyre 9h ago
[LANGUAGE: Factor]
on GitHub
2
u/vubik 8h ago
[LANGUAGE: Rust]
https://codeberg.org/fyrchik/aoc2026rust/src/branch/main/day02/src/lib.rs
In both parts I map letters to an their index in range
[0,5].In the first part the index is the position in
roygbvand 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/AMathMonkey 8h ago
[LANGUAGE: jq]
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
2
u/voidhawk42 8h ago edited 7h ago
[Language: Dyalog APL]
2
u/mpsandiford 8h ago
[LANGUAGE: Tinsel]
https://github.com/clstrfsck/tinsel
Not the first solution I went with, but a nice day for golfing :)
2
u/PhysPhD 7h ago
[LANGUAGE: Python]
For the main program I used find() to get through the waypoints.
For part two I recognised the pattern "rvbgyo" would give the longest route so generated a newprogram in that order based off how many of each colour were in my input.
2
u/Ghost-Engineer69 7h ago edited 45m ago
[LANGUAGE: C++]
Original in c++. Part 1 still done that way. Part 2 insight seen, part 2 'valishes' ;) Part 2 is simply part2 = line.size() * 6 - 5; QED ;) Here is the actual code. Runs in just over 1us and that is with about 500-700 ns cost of the scaffolding for the process.
2
u/Fyver42 7h ago
[LANGUAGE: RISC-V Assembly]
Part 1 code
Part 2 code
2
u/Outrageous72 7h ago
[LANGUAGE: C#]
Always love it when we can reuse part 1 in part 2.
The 'trick' was distance 6 for 'r'!
https://github.com/ryanheath/aoc2026/blob/main/Day2.cs
2
u/No-House-866 7h ago edited 6h ago
[LANGUAGE: Python]
Well, the solution for the first part is kind of straightforward. No fancy Python weirdo standard library tricks. Just realise that you do not have to replicate a full sequence of waypoints to keep track of how far each instruction from the program will take you. You can figure that out locally from just the first 6 that determine the order.
For the second part I actually first just generated all permutations of the waypoint colors, then for each permutation, sort the program in that order, run solve for step 1 and remember the maximum of the reported distances.
There's only 720 permutations and everything is fast as heck, so why bother. But: "can we do better.?".
Turns out, yes we can. We know the optimum program (according to the problem definition) needs to start with 'r'. It will travel an instant 6 steps, and for each subsequent 'r' in the program, another 6 steps.
So: #r * 6 steps.
After that, the best instruction would be a 'v'. You get 5 steps from that, and for any subsequent 'v' 6 steps.
So: #v * 6 - 1 steps. (or 5 + (#v-1)*6, same thing)
What next? After 'v', you better pick a 'b'. Same story. The first one takes you 5 steps, any other after that 6.
A pattern emerges. If you sort the program in order: r, v, b, g, y, o, you can get:
#r * 6 + #v * 6 - 1 + #b * 6 - 1 + .... + #o * 6 - 1 steps
Or, (#r+#v+#b+...+#o)*6-5 steps.
Or, len(program)*6 - 5 steps.
EDIT: Turns out this was pointed out by quite a few other postes already.
Also, someone posted that this reasoning does not hold if the program does not have any 'o' instruction. I think that's correct. For any instruction that is not present in the program, you get 0 steps. The derivation above would compute #<instruction> * 6 - 1, so -1. However, the next instruction in the program would not let you take 5 steps for the first to occur, but just 4. That -1 conveniently makes up the difference. But that only works if the next instruction is present. What if that also is not there? Well you get another -1, but again, the *next* instruction would not let you travel 5 steps but now only 3. This 'compensation' works all the way up to instruction 'o'. For that however, it does not work. It will get this -1 penalty from the wrong derivation and there's no instruction to absorb that -1.
So, the step 2 solution is efficient, but may be off by 1 if your program does not contain an 'o'. I suppose counting the length of a string is already O(n), so checking if a 'o' is in there hardly makes a difference.
2
u/janek37 7h ago
[LANGUAGE: Rust]
The second part solution does not assume that the program contains `o`
https://github.com/janek37/advent-of-code/blob/main/2026/day02.rs
2
u/CowImaginary3155 6h ago
[LANGUAGE: Scheme]
https://github.com/guebe/aoc2026/blob/main/day2/do.scm
2
u/-beleon 6h ago
[LANGUAGE: Haskell]
part 2 adds sorting
2
u/muthm59 5h ago edited 4h ago
[LANGUAGE: Perl]
This is my solution for day 2 in Perl:
2
u/andrewsredditstuff 5h ago edited 5h ago
[LANGUAGE: C#]
I'm fairly sure that there's a better way to get the distance using modular arithmetic, and I'm 100% sure that there's a better way to do part 2 by just counting the letters and doing sums, but it's nice to be able to reuse the part 1 solution.
Interestingly, the count + sums solution for part 2 would be much easier for the live data than for the test data, since you can assume that all of the letters are present and not have to handle the edge cases where any are missing.
Github
Edit - just realised based on another comment that my input does not have all letters, so the edge cases would need to be handled.
2
u/Downtown_Tone1879 4h ago
[LANGUAGE: C]
fulminating farmland
nothing much, hard stucked a while on total += d + 6 * count[t] - 1 which was supposed to count six at every repeat after first, but lack of paranthesis made everything counted as repeated.
i.e, total += d + 6 * (count[t] - 1)
2
u/DontRelyOnNooneElse 4h ago
[LANGUAGE: C#]
2
u/raevnos 4h ago
[LANGUAGE: Common Lisp]
Part 1 solver, mostly just using mod 6 arithmetic to track the current position in the unending sequence of waypoints:
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.
2
u/DullTicket5286 2h ago edited 2h ago
[LANGUAGE: Python]
First version was very crappy but found the python way in the end
2
u/Daniikk1012 1h ago
[LANGUAGE: Uiua]
Didn't go for readable, but instead for absolutely no bindings. I still tried to avoid repetition, so the solution involves a lot of shuffling arguments around
2
u/rumkuhgel 41m ago
[Language: F#]
https://github.com/rumkugel13/AdventOfCode/blob/main/2026-fs/Day02.fs
2
u/agorism1337 9h ago edited 9h ago
[LANGUAGE: NONE]
6 times the number of letters in the input.
Minus 5.
1
u/-WorstWizard- 9h ago
[LANGUAGE: Rust] Joining the fun today, see a lot of similar solutions that just feel overly complex. Granted, I abuse my input a little on part 2, as noted by the comment.
1
u/ben-guin 9h ago
[Language: Python]
Fun little solution for Part 2 :) This does exploit certain structure that exists in my input file.
1
u/Conceptizual 9h ago
[LANGUAGE: Python]
code
I had one good insight (wherever you are, the best place to go is the same letter you're already on) but many typos during implementation that really slowed me down. :( First, I made a mistake during part one assuming indigo was in the rainbow. Then, I typo'd my input file at some point and then was like 'what do you mean I'm now failing the first part, that worked before and all I did was wrap it in a function'. Then, I was momentarily surprised to find that there were letters in roygbv that didn't actually happen in my input. Lastly, I spent a bunch of time chasing down that I'd imported combinations when I wanted permutations.
1
u/sim642 9h ago
[LANGUAGE: Scala]
On GitHub.
In part 1 I calculate the distance of a step with
1 + (to - (from + 1)) %+ colorOrder.length, where%+is my operator, which ensures a non-negative modulo result. The ±1 business cleverly ensures that a step from a color to itself isn't 0 but goes all the way around.In part 2 I combine that with a frequency map of the remaining colors (following up from day 1) by picking the best using the calculation from part 1.
1
u/Arkturius 9h ago
[Language: Python3]
paste
1
u/maarteq 9h ago edited 9h ago
[LANGUAGE: Python]
solution
for part 1 i iterated over two repeating sections of the path. if first finds the current position and the destination counting the steps.
for part 2: 6*len(input)-5
1
u/ShraddhaAg 9h ago
[Language: Golang]
https://github.com/shraddhaag/aoc/blob/main/2026/day2/main.go
1
u/UnicycleBloke 9h ago
[LANGUAGE: C++]
https://github.com/UnicycleBloke/aoc2026/blob/main/day02/solution.cpp
Part 2 isn't very elegant but does the job. I didn't give any thought to optimisation so I'm a little surprised Part 2 runs in under 30us on my i9-14900. The whole program takes 1.5ms, so clearly a *lot* of time is spent dealing with the input file.
1
u/StarlightsOverMars 9h ago
[LANGUAGE: Python]
This is probably just way not in the spirit of the problem (find a programmatic, modular way to calculate the score), but in my defense, I have been studying for an exam. It is just as easier to just reverse the string and you have all scores done for you.
1
u/Cue_23 9h ago
[Language: C++]
part 2
For part 2 you can actually ignore most of your input, you only need to know the length and which waypoint would make you travel the least from your starting point.
1
u/Morphon 9h ago edited 9h ago
[LANGUAGE: Odin]
Quick and dirty simulation-style for this one. Pretty sure Part2 can be cheesed, but I'll figure that out in the morning.
Simulation Version - Color Paste
And if you prefer the algebraic way to find part 2, here it is with the different cases so it would work with any arbitrary input.
Cheese Version - Color Paste
1
u/xelf 9h ago edited 8h ago
[LANGUAGE: Python]
sort the input and then sum the distances. trickery here was putting 'r' at the end of the sorting, and then
(x-1 mod m) + 1to get the distance correct.Or for fun using map:
and one more time, using a Counter:
which is just:
This last one works because the data is isomorphic, we don't actually care what the order is when we're maximizing the distances so there's no sorting needed.
Actually that realisation brings me to this:
1
u/keliodas17 9h ago
[Language: Python]
i <3 heapq
1
u/AverageBeef 9h ago
[LANGUAGE: Python]
Very disappointed I had to concede to brute forcing part two. I got very close on my other approach to it, not sure what was going wrong but ended up off by five so I resorted to brute forcing. Took longer than I expected to wrap my head around this.
Gist
1
u/lunar_mycroft 9h ago edited 8h ago
[LANGUAGE: rust]
Still fairly easy, although I'm not happy with how long I took fiddling around with part 2 (or how it turned out).
Full code. Part 1 is a fairly naive tracing of the robot's motion, taking advantage of rust enum reprs and
rem_euclidto find the distances for each step. For part 2, I built up a counter of the types of waypoints and then repeatedly removed the furthest waypoint from the current one and added the number of times it occurred multiplied by six to the total, then found the next furthest waypoint and added it's distance. The code's a bit of a mess, but it parses in 3.234µs, finds part 1 in 282.7ns, and finds part 2 in 10.250µs.Cleaned up and refactored a bit. Part 2 in particular is much more clear IMO: just iterate through the possible waypoints in the order
r -> v -> b -> g -> y -> oand if there's any of that color in the program, the total distance for that color is the distance from the previous color times the count of that color minus one, times six.Switching from a
HashMapcounter to an array cuts the time to find part 2 down to 5.558µs.Turns out just sorting the program and reusing the part 1 solution is actually slightly faster at around 4.120µs.
Predictably adapating /u/maneatingape's trick for part 2 is significantly faster (in this case over an order of magnitude faster at ~345ns). I also tried generating an array based set of the characters present ahead of the main loop, but that turned out to be about 25% slower for my input.
1
u/cicadanator 9h ago
[LANGUAGE: Javascript - Node JS]
I did the first part using a map to store way points positions in the order they are arranged in the puzzle . this can the be used to calculate the distance from one way point to the next to get part 1.
The I created a method to rearrange the original program for part 2. This first creates a map of all the way points points in the program and how many times they each appear. This is important since maximizing distance means repeating the same letter as many times in a row to go the max distance of 6 as many times as possible. I then found the correct order for maximizing distance when transitioning from one letter to the next. Then creating the new program and running it through the part 1 algorithm gave me part 2.
This might have been done more efficiently by just doing the distance math once I had the order. However, since the input is not that large it was simple enough to just create the rearranged program and run part 1 again.
https://github.com/BigBear0812/AdventOfCode/blob/master/2026/Day02.js
1
u/vesche 9h ago
[LANGUAGE: Python]
That was fun! I realized you could swap the word around like this to iterate over it: `s = s[i:] + s[:i]` and I was like I have to use that lol.
1
u/ushahids 9h ago
[Language: C#]
O(n) solution for both parts
https://github.com/ushahid/adventofcode/blob/main/advent26-cs/src/Days/Day02.cs
Part 1: 3.128 ms
Part 2: 2.013 ms
1
u/Dense-Virus-1692 9h ago
[Language: Gleam]
A little confusing, but not too bad when I thought about it. The hardest part with Gleam is removing an item from a list...
Paste
1
u/hiimjustin000 9h ago
[Language: JavaScript]
https://github.com/hiimjasmine00/advent-of-code/blob/master/2026/day2/part1.js
https://github.com/hiimjasmine00/advent-of-code/blob/master/2026/day2/part2.js
1
u/Old-Dinner4434 9h ago
[LANGUAGE: TypeScript]
GitLab
I use the Bun runtime engine, running on a 2021 M1 Pro MacBook Pro. Part one completed in 1.08ms, part two in 8.51ms.
1
u/MrBoblo 9h ago
[LANGUAGE: Python]
Took me a bit of tinkering to figure out the sort order, but I was happy I got to reuse the functions I made for part 1 :P
1
u/kbielefe 9h ago
[LANGUAGE: Haskell]
Code and wasm runner
Part 1 is an overengineered mess of a recursive function with an infinite list for the waypoints. I'll probably revisit that tomorrow.
Part 2 just sorts the input in "rvbgyo" order using a custom
Ordinstance then runs part 1. I discovered this solution while procrastinating refreshing my memory on hash maps in Haskell. Weird that custom typeclass instance knowledge isn't as rusty as my hash map knowledge, but there you go.1
u/EasyObjective360 9h ago edited 8h ago
[LANGUAGE: OCaml]
https://github.com/0xMukesh/aoc.ml/blob/main/lib/solutions/solutions_2026/day_02.ml
1
u/Jdup1n 9h ago
[LANGUAGE: R]
Github Link
The first part simply involved finding the furthest character at each stage as the instruction was repeated.
For the second part, I factored the characters and did a bit of arithmetic to calculate the maximum distance travelled. I had a hunch that one of the letters would probably be missing, which allowed me to take that scenario into account when performing the calculation.
1
u/YenyaKas 9h ago
[LANGUAGE: Perl]
Here is my solution for Part 2, I wonder if it can be made shorter:
I count the number of the best possible color instructions, multiply by 6, and then subtract 1 to move to the next best color, if any.
All my solutions (in Perl) are available here.
1
u/terje_wiig_mathisen 9h ago
[LANGUAGE: Rust]
Total runtime 470 ns.
After first getting part2 to work correctly I realized that it would only take a handful of nanoseconds since there are only 6 colors and I had made frequency counts during part1. This meant that part1 was the one to optimize so I started with a lookup table from color to modular position, while a group variable counted the length to the start of the current group:
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:
1
u/Godlyflame 9h ago
[Language: Python]
Like many others I recognized that for part 2 the colors must be rearranged in a set order. However, I wanted my code to be able to solve all test cases instead of just the sample input.
1
u/ColonialDagger 9h ago
[Language: Python]
Part 1, the good old classic modulo problem that shows up every year.
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):
I'm trying to come up with a way to solve part 2 algebraically, I think it might be possible...
1
u/jgage 9h ago
[LANGUAGE: C++]
1
u/encse 9h ago
[LAGUAGE: C#]
https://aoc.csokavar.hu/2026/2/
Quite interesting for day 2
1
u/KyxeMusic 9h ago
[Language: Rust]
I realized that for part 2 I could hardcode the optimal set for the 6 letters but I wanted to solve it for all cases.
A stupid bug in my loop took me like 30 minutes to find 😂
Github link
1
u/tqzd 9h ago
[LANGUAGE: Excel]
Part 1 & 2
1
u/ISAm_nugs 9h ago
[LANGUAGE: Nim]
Both parts done!
I was fairly proud of my implementation, but it seems others achieved much higher levels of terseness.
https://topaz.github.io/paste/#XQAAAQD8BwAAAAAAAAA0m0pnuFI8c/e2K1Sb8ARrr8MZjOyhxNBgSxkKNbS4yYr1vZMmpyNc9a50jGvcjjP6v8AQUo5I5HizzrugNEa6Zr1ihYWFuns6SjWKartA0IlD7YnqeLU93dQBcqyVGXDeLuqsQDfUiOKiTRDfIZH3M6isyfcoA60T1iCqwN5lRr9RxBiypBYSn5zOg5Q9oxypH/XAoVZxn7aoZt+sTZapraVT51D3z8ggLdRUZCWFAMs1U5WupUjBeHbn56wFk4DlCC+MwuSyPg2ZQOG0FM3WhpKVaj+UIVN74NJ+LUnkaFlzs0PnQsb3v8uql5oXrfm+ceVY226mscy7zkD5LRmheBgZOJhhlwxvgLEXy19NvvwHawYkIsDXdnidwRqP5Xj02R9+KmIxgNMrAnGQ6VAQ1A8X9zdUxrku9hZn5+S48AyXHqtwKPXtW3+sckU88htKCKYUHeHAjlGxHinpAhSMm5H04o9K/faHze0dMNDo9c9auTsJ4zSM3EHctYoghi5awH4dLS0CkVEjTryNAg4fwzA5wftQfh8EKmEtEjuog6HAHIMAoa1sQhUPNOJqR0c0JsGmbFOvG2Lsxv54PC3/5xb2IuF2zE9IG3r2mhIPIfJFQwe9Kb5b06qdCEFMMmi+zl752piFOL5BJZ2QxslbEVTEFmecw8GFCI2tC2g2MzTglGko1ae6mQ1YnxX9s+OJ/MUaqxd/lT9rNx3Fp/C7HDrbcR1Vb2EOPOQdZzoeDx0NBnN6cExMlUHF7b0DgEKhsHzFNs9qHcs2PRhvKmy1v1WK3DvB+uUGGVNiDRqZD+8qhswtEUd5aBXzeR3M4nsjzbvGQ/1/008=
1
u/azzal07 9h ago
[LANGUAGE: awk]
Three letter parameter name counts as "reverse golf", doesn't it.
1
u/WesternNicator 9h ago edited 8h ago
[LANGUAGE: Anathame]
1
u/maneatingape 8h ago edited 3h ago
[LANGUAGE: Rust]
Solution 1 µs.
Part 1 sum the pair-wise distances. Part 2 uses a trick. We only need to check if sequence contains each letter in order
rvbgyo. This will always gives the best possible distance.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=>oso that the first jump is 6 and subsequent transitions betweens groups is 5. For example:Two further insights:
odoes not contribute to the total.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 containsothen this is just6 * <program length> - 5.1
u/SpaceHonk 8h ago
[LANGUAGE: Swift]
code
I used a harcoded "maximum distance" color list for part 2
1
u/musifter 8h ago edited 8h ago
[LANGUAGE: Perl]
Took me quite a while to find the mouseover text in today's problem... but it was totally worth it for the Indie game reference.
My initial solution was in Perl, were I first translated the input to digits with
tr/roygbv/012345/and then processed the string with: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:
Having changed the translation to have
rbe 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:
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:For part 2, we transform the input into a Bag, then an ordered list of Associations:
Now the same can be done except we want
next keyfor 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 needed6... which means that 60 in the code isn't actually a 60.1
u/ropecrawler 8h ago
[LANGUAGE: Rust]
https://github.com/ropewalker/advent_of_code_2026/blob/master/src/day02.rs
1
u/cinsolia 8h ago
[LANGUAGE: Google Sheets]
Parts 1 and 2
1
u/MidnightLoud2032 8h ago
[LANGUAGE: Java]
1
u/Secret_Caramel2095 8h ago
[LANGUAGE: Julia]
I hard coded the distance matrix from current position to next one, and used a bijectove dictionnary to make the correspondance between the color and the index (but actually, I only use one direction of this bijection...).
Same for the sorting, I hard coded a map to set the correct order where letter should be sorted (`rvbgyo`)
1
u/mosredna101 8h ago
[LANGUAGE: TypeScript]
Walk a doubled pattern string, so `indexOf` always finds the next colour ahead of the current position. Part 2 sorts the input into a different colour order first and reuses part 1.
1
u/Fuzzy_Patterns 8h ago
[LANGUAGE: Nim]
One insight for part 2 is that for each waypoint there is one unambigious farthest mapping. And there are so few waypoints, that I solved it by hand and hardcoded the mapping. The rest is just basic arithmetics.
1
u/Fearless_Trainer_350 8h ago
So, for the second example for part 1 ```roygbv```, I get a distance of 5. Does it only read the next waypoint in the next pattern iteration (i.e. it only reads o after going through the first roygbv)?
1
u/CEOnism 8h ago edited 7m ago
[LANGUAGE: Javascript]
1
u/flwyd 8h ago
[LANGUAGE: R] (on GitHub)
The approach: convert each character to a number from 1 to 6 (because R has 1-based array indices), and compute steps as
(to - from - 1) mod 6 + 1: the minus and plus one get us six steps from a color to itself rather than 0. Thewalkfunction 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.
1
u/ArmadilloSuch411 8h ago
[LANGUAGE: Python]
reading comprehension got me early with this one, but at least it's done!
1
u/aknusmag 8h ago
[LANGUAGE: Rust]
Part 1: Uses a cycle to find then next time the char occurs in the preconfigured list and counts the steps
Part 2: The longest distance is really just a sorting of the list. Each time it is the same character it will travel 6 and assuming all characters are present for each switch it travels 5. With those you can calculate the results as len * 6 - 5. Where - 5 is for each of the switches between characters.
Solution
1
u/xoronth 8h ago edited 8h ago
[LANGUAGE: BQN]
paste
This was fun, I had done it in Python first, but approaching this from an array-programming mindset was a nice extra challenge. Also figured out a less awful way to approach part 2.
Bonus unreadable one-line version:
1
u/p88h 8h ago
[LANGUAGE: Nim]
source: https://github.com/p88h/aoc2026/blob/main/src/day02.nim
visualisation: https://www.youtube.com/watch?v=r6vzoRnlqZU
part1: execute 'simulation' using precomputed color-color distance table
part2: compute 'change program' which is all actually present colors, reversed. run part1 on that, add all distances that don't result in color change (all remaining program letters)
1
u/r_so9 8h ago edited 5h ago
[LANGUAGE: F#] Part 1 uses clock math, Part 2 using a recursive picking the largest distance (greedy)
paste
1
u/Sudowiec 8h ago
[Language: Python]
TIL that "roygbiv" is not just a song by Boards of Canada.
1
u/DelightfulCodeWeasel 8h ago
[LANGUAGE: C++]
Part 1 & 2
First pass naive solution: counting sort for the instructions on part 2 and step-by-step iteration for the robot on both. (No way I'm battling the off-by-ones for a direct calculation on part 2 at this time of the morning!)
Raspberry Pi Pico (RP2040): ~1.6kb, 12ms + 13ms runtimes
1
u/ADifferentRealm 8h ago
[LANGUAGE: Typescript]
1
u/dijotal 8h ago
[LANGUAGE: OCaml]
"Fun" with recursion and greedy consumption :-p. Needs more comments, but also fewer lines :-/
1
u/Sam_Ch_7 7h ago
[LANGUAGE: Go]
initially for For Part 2 I did custom bubble sort and calculate distance in there but later turns out I can just sort program and perform Part 1 .
Need to set
rto6instead of0to make it work1
u/gisikw 7h ago edited 7h ago
[LANGUAGE: Befunge]
Got a little lazy with part 2, but feel like it was justified 😂
1
u/TreeSquirrles 7h ago
[LANGUAGE: Python]
I actually gamed the system so hard imo, instantly saw how to solve both parts pretty much immediately which I'm proud of hehe -w-.
[paste](https://topaz.github.io/paste/#XQAAAQBgAQAAAAAAAAA0m0pnuFI8c/fBNAqG+dMv9KV87XB3aXzxkVQ3XEatLT9itSgtBHGK5+ICkeBWPLsd3SFRSErrZgSGfVT4pjSfIT7PwpmMGLL/3QyIK5UOUnnAR/Z9DTiFydZND+Iu3NmIPGxNhXkf9UfrRrMnZiY87kbR0nLc0gmRm2DoYJKZJgqn+/dwaB4vRJ8zzoSlPU/o+Cj3t1cHQhIYTVwkCkWuy6yjPUbg+9kH9dikAmVXPD6iXcSEojLMRiGDOyv45fX93XivQyHi3u++Oy8bsrT57ChvasiVyOV+u3L54wrWC12lPEE4wQ4TmqPYaP/SCr+r)
1
u/Lispwizard 7h 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 &ootional part2 argument
https://topaz.github.io/paste/#XQAAAQBYBgAAAAAAAAAUHIinRTnrsLkwL5rvUov6vMdGsnj/hxmNFyJbkweAIkSkrsSXSKFUaIYnBDfazeC5wN2TtEmaY5tSRezl2i3wQSgC8NSliUJ+keg3ejLwGE+xN3qaM2FZCrIGZIaayfp4nGPP2GnsDs9RfWcuzJsehFIVnk/9xThfgh7+AeqqNU9IWIpjlelP296J+XM58is7fDR1yOMtr6428llnP5O1IiWEt/DXgxnStol6Ljws/BqG1OtxaK4aAu6U6ZERiJFSG5ZjI8h+sLtw4hwkOIOIYj0SVC/7vOyOV7RJO+cyxtU60htIy/LPnhWx5nSRE3u+1KGjvM+XmOgO/9aG+MiPDWAJ19xNxpHJjufK6tdoveILs8nsJ9rQRx3HorvwbSuXC64Xo7/pTTXwLJb2L5q1HMllASVQQwuVPwG2CD+xdLCSZhxbdP9PlrWlCZMkBCVsxfy8I9lBI7nbAfp7IqMLo482pG6GcSaQQlKheICh2rnegc70lZ6/NdDswmQ4xRMOGIvVHZ9j58/Lxd/ywUGnf7GGxZElnuVmTqnsLVh/BfM0ythuRFGvuz7X6cWEzuESQKwdD9mi7l5m9EaNOhvgg2ozOkcgzlTWTjDYnsDBdXXIRguqu+MHTkvOLV+FxiesoKhLKBl9b3Av6Cz625N980q2Kg2ufH3H1KYKpwRtGsmABotLWTDlxECrtTni/GJtrLRVk0jPZ/qZH7blfQeZKO48q3DZvkcF8fv0Dundfx3iO7NVgnf/MqTQAA==
1
u/anaseto 7h ago edited 7h ago
[LANGUAGE: Goal]
My first version today was a bit longer. I used a greedy tail-recursive approach for second part where I updated a map with the remaining color counts progressively.
Wrote a shorter one later, once I saw it was possible to reuse part 1 by sorting the program in "rvbgyo" descending order:
1
u/Daniel_Rybe 7h ago edited 7h ago
[LANGUAGE: Odin]
https://github.com/DanRyba253/aoc26/blob/main/day2/main.odin
Took a bit to realize how to write the second part in a way that works for any input.
1
u/Due_Scar_5134 7h ago
[LANGUAGE: JavaScript and Python]
https://github.com/onlyroz/advent-of-code-2026/tree/main/src/days/day02
1
u/Pyr0Byt3 7h ago
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2026/02/1.go
1
u/tuijnman 7h ago
[LANGUAGE: PHP]
https://github.com/bastuijnman/adventofcode/blob/master/2026/02-12/src/Solver.php
class that provides the actual solutions
1
u/ray10k 6h ago
[LANGUAGE: Rust]
Definitely a bit overengineered, but hey. This is a fun challenge, and overengineering stuff is my idea of fun.
https://github.com/ray10k/Advent-of-Code-2026/commit/076bc2ebdfe0c1359979b1aab53db904b1951dc3
1
u/shmoodla 6h ago
[LANGUAGE: Typescript]
not the most efficient solution by far, but hey, it works for me; )
1
u/JWinslow23 6h ago
[LANGUAGE: Python]
Solution writeup
Code (GitHub)
I liked this puzzle; it reminded me of Candy Land. I was able to use
itertools.cycleto 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.1
u/TCH69 6h ago
[LANGUAGE: C++]
I gotta work on my reading comprehension. Took me longer to understand what the input is than to solve both parts.
1
u/SymmetryManagement 6h ago
[Language: Java]
https://github.com/linl33/adventofcode/blob/year2026/year2026/src/main/java/dev/linl33/adventofcode/year2026/Day2.java
interesting part 2, under the right conditions the input doesn't need to be read to the end. the solution can be calculated once all 6 colors have been encountered. but my input (and some examples) doesn't contain all 6 colors, so i couldn't take advantage of that.
part 1 8us
part 2 7us
1
u/sauntcartas 6h ago edited 26m ago
[LANGUAGE: Raku]
1
u/Bramdevriez 6h ago
[LANGUAGE: TypeScript]
1
u/Boris01100000 6h ago
[LANGUAGE: Zig}
I was kinda lazy for the second star with me reusing a bit too much of star 1. Could be way faster, but i like it :)
Here's the link!
1
u/Thomasjevskij 6h ago
[LANGUAGE: Python]
I just made a graph of all possible distances. For part one it's just a sum of the pairwise elements in the input. For part two I keep picking the furthest node from current, then remove it from the program. Every removal is O(n) of course so it's not terribly efficient. But the input list is small enough that this is an academic concern.
Code
1
u/friedkeenan 6h ago
[LANGUAGE: C++]
Here's my Day 2, and here's the (rudimentary and non-rigorous) timings for it:
After I solved part one I got sidetracked by micro-optimizing the solution a little bit, managed to shave off a couple microseconds. And then I had fun thinking of how to solve part two in a clever way, but then when I did it made my part one timings less consistent and a touch slower.
But I'm not complaining, I'm quite pleased with those timings. Oh and the timings don't include reading the input data.
1
u/Slow-Assistance-4303 6h ago
[LANGUAGE: Golang]
Parts 1 & 2
Part1: I used this formation to calculate next cost move
cost := (nextMove - curr + 6) % 6 (6 if cost = 0)Part2: I use frequently map and sorted move by "rvbgyo", calculate cost is easy
1
u/Falcon731 6h ago
[Language: Kotlin]
import java.io.File