r/adventofcode • u/daggerdragon • 18h 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?
25
Upvotes
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 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.
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: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.EDIT: And part 2.
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:
EDIT: A little cleanup and reordering of things on the stack to golf part 2 down a bunch of strokes.
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, thereducefunction 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.2
u/valhesh 5h ago edited 5h ago
[LANGUAGE: C++]
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 :/
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
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.
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.
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
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:
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).
7
u/JustinHuPrime 18h 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.
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:
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/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.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/Street-Apartment-512 11h ago
[Language: UIUA]
2
u/agorism1337 17h ago edited 17h ago
[LANGUAGE: NONE]
6 times the number of letters in the input.
Minus 5.
11
u/4HbQ 18h ago edited 14h 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.
5
u/TallPeppermintMocha 18h ago
[Language: Python] Both parts solved using a sort key
5
u/heijp06 17h ago edited 12h 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).
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.
I also made it work with piped or redirected input. https://github.com/ednl/adventofcode/blob/main/2026/02.c
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!
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 17h ago edited 9h 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 17h ago
[Language: Uiua]
4
u/TumbleweedCold3542 17h ago
[LANGUAGE: OCaml]
First time working through anything in OCaml. It's definitely been an interesting experience so far.
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
and now it should work for any amount of waypoints missing
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.
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.
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
4
u/p4bl0 13h ago
[LANGUAGE: Shell + whatever you used for part 1]
Solution to part 2 assuming
p1solves part 1 by reading the input on its stdin :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:
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.
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
tevis initialized topagh, not your filthy, sniveling, Terran symbol0. 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 givingmaH javinstead of16for the first example in part 1. There isn't anelsestatement, so instead of sayingif (var > 0) { ... } else { ... }, I have to sayif (var > 0) { ... }; if (var == 0) { ... }. The syntax is mostly just RPN, but with everything spelled out in Klingon, like+beingtIchel...For example, take the line:
"-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 firsttevas 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.
Part 1, "readable" (ha ha!)
4
u/DullTicket5286 10h ago edited 10h ago
[LANGUAGE: Python]
First version was very crappy but found the python way in the end
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
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:
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
1
u/encse 17h ago
[LAGUAGE: C#]
https://aoc.csokavar.hu/2026/2/
Quite interesting for day 2
1
u/ISAm_nugs 16h 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/TreeSquirrles 15h 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 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/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/dantose 7h ago edited 5h ago
[language: Powershell]
I decided to just convert everything into positions so I can just do math.
Part 1:
Part 2:
1
u/e_blake 4h ago edited 3h ago
[LANGUAGE: mfour] [Advent Games]
I'm grokking that as "using words, not digits, is good". My mfour solution swaps in words for all digits, and avoids fifthglyph.
That calls for fun quotation! A partial look at my solution:
Run as:
1
u/Latter-Negotiation33 4h ago edited 4h ago
[LANGUAGE: Odin]
Link
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:
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 18h ago
[Language: Clojure]
Not as proud of this one lol. Did everything very manually.
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.
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.
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 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/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]
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.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.3
u/cinsolia 16h ago
[LANGUAGE: Google Sheets]
Parts 1 and 2
3
u/AMathMonkey 16h 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
3
u/voidhawk42 16h ago edited 15h ago
[Language: Dyalog APL]
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 :)
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.
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.
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.
3
u/gisikw 15h ago edited 15h ago
[LANGUAGE: Befunge]
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
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:
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.
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
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.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.3
u/CowImaginary3155 14h ago
[LANGUAGE: Scheme]
https://github.com/guebe/aoc2026/blob/main/day2/do.scm
3
u/-beleon 14h ago
[LANGUAGE: Haskell]
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:
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.
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)
3
u/DontRelyOnNooneElse 12h ago
[LANGUAGE: C#]
3
u/WolfRushHour 12h ago edited 17m ago
[LANGUAGE: Julia]
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 ourprogram.Then, stepping inside the
distance-function,diffof that array calculates the signed difference between two adjacent elements from left to right, which gets us an array of differences calleddeltashere. If an element ofdeltasis positive this is exactly the distance we go in that step. If the difference is0, for example when going from state 3 to state 3, we want to go the maximum distance of6instead. If the difference is negative, e.g.-2, e.g. when going from state 3 to state 1, we cross a0and therefore have to go a distance of4instead. In each of those cases we needed to add a distance of6to that difference (to0and to-2respectively, in this example).deltas.<(1)creates an array of typeBitVectorof the same length asdeltasto indicate where such "overshooting" happens. Multiplied by6gives an array of the same length asdeltasbut with a6for the<(1)condition met and a0otherwise. That array is added to the signed differences indeltas. Wesumup the resulting distances of all those steps.For part 2 we sort the
program-array first to create as many0-steps as possible for a maximum of6-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 usereverse(sort(program))orsort(program, rev=true)for that. But because we're going to take differences later on anyway this is equivalent to multiplyingsort(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!3
u/erikade 9h ago edited 4h ago
[LANGUAGE: Go]
Today's solution is really cute (20+ LoC) and runs accordingly (
550ns520ns mbairM4/24GB).https://github.com/erik-adelbert/aoc/blob/main/2026/2/aoc2.go
Writeup is in the 2026/README
Happy coding everyone!
3
u/rumkuhgel 8h ago
[Language: F#]
https://github.com/rumkugel13/AdventOfCode/blob/main/2026-fs/Day02.fs
3
u/Parzival_Perce 7h ago
[LANGUAGE: Python]
I'm not a huge fan of the need to write
or 6but whatever ill take it3
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]
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 ^
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
1
u/yoni-kosiner 18h 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 18h ago edited 18h ago
[LANGUAGE: Python]https://aoc2026.knollfear.com/day/2. My day 2 solver with visualizations.
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
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
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 18h ago
[LANGUAGE: TypeScript]
https://github.com/mikeyloboto/aoc2026/tree/master/02
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)+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 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]
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/mendelmunkis 18h ago
[LANGUAGE: C]
My habit of wc -L ing my input was useful!
Alternate link for DDOS
93 μs/34 μs
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/chickenthechicken 18h 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 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
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.
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!
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...
2
u/lluque8 18h ago
[LANGUAGE: Scala]
code
2
u/snubian 17h ago edited 17h ago
[LANGUAGE: R]
2
u/throwaway6560192 17h ago
[LANGUAGE: Python]
Just take your function from p1 to calculate the distance of a program, and...
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
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 17h ago edited 17h 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 17h 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/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}: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/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
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.2
u/EasyObjective360 17h ago edited 16h ago
[LANGUAGE: OCaml]
https://github.com/0xMukesh/aoc.ml/blob/main/lib/solutions/solutions_2026/day_02.ml
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.
2
u/YenyaKas 17h 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.
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:
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:
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.
2
u/ColonialDagger 17h 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...
2
u/jgage 17h ago
[LANGUAGE: C++]
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
2
u/azzal07 16h ago
[LANGUAGE: awk]
Three letter parameter name counts as "reverse golf", doesn't it.
2
u/WesternNicator 16h ago edited 16h ago
[LANGUAGE: Anathame]
2
u/SpaceHonk 16h ago
[LANGUAGE: Swift]
code
I used a harcoded "maximum distance" color list for part 2
2
u/ropecrawler 16h ago
[LANGUAGE: Rust]
https://github.com/ropewalker/advent_of_code_2026/blob/master/src/day02.rs
2
u/MidnightLoud2032 16h ago
[LANGUAGE: Java]
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`)
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.
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.
2
u/CEOnism 16h ago edited 8h ago
[LANGUAGE: Javascript]
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. 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.
2
u/ArmadilloSuch411 16h ago
[LANGUAGE: Python]
reading comprehension got me early with this one, but at least it's done!
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
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:
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)
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.
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
2
u/ADifferentRealm 15h ago
[LANGUAGE: Typescript]
2
u/dijotal 15h ago
[LANGUAGE: OCaml]
"Fun" with recursion and greedy consumption :-p. Needs more comments, but also fewer lines :-/
2
u/super_kitakami_sama 15h ago
[LANGUAGE: Go]
paste
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
rto6instead of0to make it work2
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.
2
u/Due_Scar_5134 15h ago
[LANGUAGE: JavaScript and Python]
https://github.com/onlyroz/advent-of-code-2026/tree/main/src/days/day02
2
u/Pyr0Byt3 15h ago
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2026/02/1.go
2
u/tuijnman 15h ago
[LANGUAGE: PHP]
https://github.com/bastuijnman/adventofcode/blob/master/2026/02-12/src/Solver.php
class that provides the actual solutions
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; )
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.
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
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]
2
u/Bramdevriez 14h ago
[LANGUAGE: TypeScript]
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:
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
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]
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:Create a color counter for the input.Jump on the current color as many times we can and zero out its counter.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.
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/sakhre 13h ago
[LANGUAGE: Haskell]
https://github.com/Malipf/AdventOfCode2026/blob/main/day2.hs
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]
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.
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
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