r/adventofcode • u/daggerdragon • 2h ago
SOLUTION MEGATHREAD -❄️- 2026 Day 5 Solutions -❄️-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
AoC Community Fun 2026: The Advent Games
- Submissions megathread is unlocked!
- 12 DAYS remaining until the submissions deadline on December 17 at 18:00 EST!
Today's Event: Iron Chef Holiday Special
"Catherine, if this turkey tastes half as good as it looks, I think we're all in for a very big treat!"
— Clark Griswold, National Lampoon's Christmas Vacation (1989)
Today's schedule possibly consists of:
Appetizer and Aperitif Rounds
- Use up what's in your fridge with all of those semi-sentient leftovers excavated from the back of the fridge
- Deliberately use deprecated functionality
- Program using old codebases
- The
older the expiration datefiner the vintage, the more we'll enjoy it!
- The
Main Course Qualifications
- Solve today's puzzle using a food-themed programming language
- Bake or cook us something delicious
Dessert Finales
- Show us cookies, citrus, and/or fancy bread in/on/near your holiday tree/menorah/festive kitsch
- Show us your 1337 hot cocoa recipe (or other beverage of choice)
This prompt is totally not bait for our resident Iron Coders and/or some AoC regulars who promised us tasty pictures
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 5: Rhythmic Factory ---
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!
- State which language(s) your solution uses with
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
4
Upvotes
3
u/jonathan_paulson 1h ago
[LANGUAGE: Python]
Code. Video.
BFS! I lazily hard-coded the buttons and was punished for it by messing up 1 of the hard-codings costing me a wrong answer on part 1. Whoops!
3
u/Kermitnirmit 1h ago
[LANGUAGE: Python]
did the regular brute force for p1. quickly recognized that it's jsut bfs for part 2... https://github.com/kermitnirmit/Advent-of-Code-2026/blob/main/day_05/solution.py fun day. first one doing it live this year
3
u/michelkraemer 1h ago
[LANGUAGE: Rust]
Solution
Mostly a parsing task today. The trick for part 2 is that you have to make sure you don't visit the same number multiple times.
During the solve, I started with keeping the button strings around all the time, which allowed my to use
format!("{value:o}")to convert a number to octal andvalue.replace(a, b)to replace digitawithbin the string. I then cleaned up the code and replaced the strings withusize.Finally, I removed the
HashSetI initially used to avoid visiting numbers again and replaced it with a simpleVec<bool>because we know that values in part 1 and 2 never exceed 999 and 9999 respectively.The whole program now runs in 289µs.
3
u/msschmitt 47m ago
[LANGUAGE: Python 3]
Part 1. Part 2
Part 2 is a recursive function, that goes somewhere between 3,000 and 4,000 levels deep. It stops any time it gets a number it's already seen. It ends up with 8,933 distinct numbers out of 10,000 possibilities.
2
u/hugh_tc 1h ago edited 1h ago
[LANGUAGE: Python 3]
I figured it would be faster to manually translate my input into Python, so I did that for speed. (It has been mildly censored, to conform to the input-sharing rules...!)
paste
My cleaned-up works for general inputs, though. Part 1 simply reduces to find the values reachable in three presses. For Part 2, I had to pause for a moment to think through how to work with infinite sequences and detect convergence of iteration in Python:
Using this, Part 2 is just "beginning with {0}, what's the fixpoint of the function that adds every value reachable in one press (below 10000)?"
2
u/Ok-Bus4754 1h ago edited 1h ago
[Language: Python]
it maybe luck or intuation , but i did part 1 using bfs part 2 was straight forward, i was expecting something harder today, but seems that tomorrow will do the trick
https://github.com/Fadi88/AoC/blob/master/2026/days/day05/solution.py
p1: 50 us, p2: 21 ms
will port later to rust and share both benchmarks
2
u/4HbQ 1h ago edited 55m ago
[LANGUAGE: Python] 16 lines.
Kept it long and readable today. (At least by my standards.)
Today's Python trick is the match statement, that allows us to handle button presses like this:
2
u/AYM123 1h ago
[LANGUAGE: Rust]
felt like today's problem was simpler than yesterdays, nevertheless its a nice introduction to graph-ish problems
open to any ideas to make my part 2 faster.
part 1: 12µs
part 2: 1.7ms
github
2
u/imperfect-fourth 56m ago
[LANGUAGE: Nix]
Day 5
hopefully the difficulty picks up soon
2
u/FCBStar-of-the-South 50m ago edited 47m ago
[Language: Python]
paste
Simple BFS, just decided to hard code the buttons instead of trying to do parsing.
Only test buttons shown to hide the real input
2
u/DBSmiley 49m ago edited 43m ago
[Language: Kotlin]
Solution
Wanted to "over-design" the solution a bit just to play with Kotlin sealed interface.
Makes the depth-first search nice and pretty on Part-2 (Part-1 is similar, but has an extra search node field for tracking button presses - this makes Part-2 easier if you understand the basics of cycle avoidance).
Since a lot of people are posting their button-parsing, here's mine. Why be clever when I can just be simple:
2
u/xelf 42m ago edited 11m ago
[LANGUAGE: Python]
This was a fun one. My initial thought was "you can probably get every combination" and tried submitting
sum(range(10000))just in case it worked.It did not. =)
Another approach using a dict:
Here I edited my input to add the '-' and 'd'
2
u/maneatingape 33m ago edited 25m ago
[LANGUAGE: Rust]
Solution
401 µs284 µs.BFS for both parts.
1
u/davidsharick 1h ago
[LANGUAGE: Python]
Brute forced all possible options for part 1, used a set to track seen values and tried all buttons on all such values until nothing new came up for part 2.
Code
1
u/ChrisMan174 1h ago
[LANGUAGE: Python 3]
Manually wrote in the test/real inputs direct as lambdas, then ran graph traversal using each one as an edge
paste
1
u/1234abcdcba4321 1h ago
[LANGUAGE: JavaScript] paste
Nothing special here, should be roughly the same as everyone else's. I used a recursive function to do the search but of course any variation works fine. Hardcoded it for my input, so I replaced it with coding for the example in this paste (didn't need to use the example for debugging today so this was produced afterwards).
I had to look up Number.prototype.toString because I completely forgot that was how you do it; I'm used to the
""+vcoercion I use for base 10 conversions.1
u/captainAwesomePants 1h ago
[LANGUAGE: Python]
paste
Felt like doing this politely with classes because it seems like whenever I try to cheat it takes longer.
Nice to see that there are still completely normal, boring BFS searches with no terrifying gimmicks sometimes.
1
u/NullT3rminated 1h ago
[LANGUAGE: Clojure]
Longest parse function so far 😎
1
u/No_Mobile_8915 1h ago
[LANGUAGE: Python]
part1:
A BFS, starting with 0. For three iterations, you apply every available button to every value in the current set to explore. Using a set deduplicates the results and discards any values you've already encountered, as there's no point exploring the same state twice.
After three iterations, sum the set of all discovered values.
paste
part2:
Exactly the same BFS as part 1, but discard any results greater than 9999 and continue until the set to explore is empty rather than stopping after three iterations.
paste
Runtimes: Apple M3 pro
part1:
runtime: 0.0001s
part2:
runtime: 0.0178s
1
u/morgoth1145 1h ago edited 22m ago
[LANGUAGE: Python] code video
This is a fun problem (despite me bungling it a bit)! Parsing the buttons was a tad tedious but not too bad. Unfortunately I had my button loop inside my state loop initially (opposite to the code above). Since I'm reusing the same variable for the display state and the modified number the next iteration of the button loop started from the modified state! This ended up creating giant, monster numbers and a completely bogus answer. I literally had to go down to simulating only one button press to notice, oof. Lost about 2:25 to that silly bug but it could have been worse.
Thankfully I was already prepared for part 2 since I was handling already seen states so nothing much to mention there.
Edit: Cleaned up code (finally) - u/4HbQ reminded me of
matchwhich I keep forgetting to try so I set out to give it a try...only I had Python 3.9 installed. Upgrading was fun - Python 3.14 broke my workflow and needed a patch in my setup/launcher script! (And Python 3.15 doesn't have a pre-built version ofgoogle-re2which my solve template relies on!) Thankfully with that out of the way I was able to get my rewrite under way.Now it uses
match, lambdas for each button, and I use a set comprehension (including the walrus operator!) for each iteration. A lot of fanciness now!1
u/xoronth 1h ago
[LANGUAGE: Python]
paste
Uhh... not much to say tbh, I just brute forced part 1 and then fumbled around for a recursive solution for part 2 with filtering... and it... worked...?
Sure I guess.
1
u/Mikey_Loboto 1h ago
[LANGUAGE: TypeScript]
GitHub
Hm, that was easier than last couple of days for some reason.
1
u/AKSrandom 1h ago edited 1h ago
[LANGUAGE: Python]
code
Straightforward problem today as well, enjoyable nonetheless, lambdas and wrappers, my beloved.
Also lol, this indeed was the best name I came up for the part 2 decorator
1
u/agorism1337 1h ago edited 51m ago
[LANGUAGE: AWK]
github 27:25/42:30
I kind of psyched myself out for part 2.
There were like 3 places to change in the code, and once I changed all 3 it worked fine. But I kept wanting to do them one at a time and run tests in between, and then I wanted to know exactly why those tests were failing.
1
u/TreeSquirrles 1h ago
[LANGUAGE: Python]
wow, as a non CS person, I'm actually surprised I solved it so fast.
Part 1: code
I was actually so stumped on how to do this one for a good 10 minutes. And then I guessed I could just brute force everything
Part 2: code
I think I took around 45 minutes? Not too shabby I guess.
1
u/BradleySigma 1h ago edited 1h ago
[LANGUAGE: Python]
1
u/yieldtoben 1h ago edited 22m ago
[LANGUAGE: PHP]
PHP 8.6.0 paste
Execution time: 0.0044 seconds
Peak memory: 1.4595 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
1
u/DFreiberg 1h ago
[LANGUAGE: Wolfram Mathematica]
Manually typing in my inputs and nesting them took a couple minutes. Making the parser automatic took almost an hour of struggling through Mathematica's various
Evaluate[]andHold[]options. And it still doesn't completely work; I eventually decided to solve the error message it gave me by wrapping the offending line inQuiet[], so that I don't have to look at the error anymore.Setup:
Part 1:
Part 2:
1
u/Crusaderkingo2027 1h ago
[LANGUAGE: Python]
This reminded me of the recursion and dynamic programming lab assignments I used to do in college.
Part 1:
Part 2:
1
u/TiCoinCoin 59m ago
[LANGUAGE: Python]
Day 5
I misinterpreted the P2 "any number of buttons" and went for bruteforce with len(input) buttons pushed. As I was plugging my laptop to let it run, I realized I was wrong, and was forced to think again. Surprisingly, I found a way. Not a super fast one, but a reasonable one (18sec with python, down to 2.5sec with pypy).
I used P1 and for each new number reached during the cycle, I use it as a new possible start for the next loop instead of "0".
1
u/honey-pony 59m ago
[LANGUAGE: PonieScript]
For once I've actually cleaned up my code a little bit. All of the common logic has been refactored into a third file. Although, I could also just do everything in one file. Whatever.
Pretty satisfying puzzle today. It was very satisfying to use the closures in my language as they're a tricky feature to implement. I had also implemented this Rust-style syntax for lambda shorthand but haven't actually used it for anything but test code yet, so it was satisfying to have a real application for it.
Link to my code: https://github.com/HoneyPony/poniescript-aoc2026/tree/main/day05
Timing information: 0.15 ms to do part one, 1.4 ms to do part two.
1
u/Wayoshi 58m ago
[LANGUAGE: Python3] paste
Misread the first command as overwriting the value instead of adding a digit (equivalent to 10 * val + x), then had the wrong itertools helper - not combinations with replacement, but product with repeat argument specified (both very unusual cases for my time with itertools!).
Part 2 is a surprisingly simple bfs/dfs, compared to what I have went through in years past (been doing these since 2023).
1
u/Andreasnl 55m ago edited 47m ago
[LANGUAGE: Uiua]
1
u/TheZigerionScammer 51m ago edited 47m ago
[LANGUAGE: Python]
A pretty straightforward problem today. Most of my time was spent typing up the instructions to parse the input and assign all the correct functions to each button, then make the different parts of the program convert from strings to integers and back again properly. Otherwise the program works as a simple BFS, taking the initial state of each string, applying the effects of each button to it and appending them to a queue. I also wasn't sure if the 1st button would append a digit to the left or right of the string, I assumed it worked like a real microwave and appended it to the right, and that was correct, but it wasn't clear from the problem statement as far as I could tell. My main bug was thinking I knew how to convert to octals in Python, I thought it was sufficient to write
for example but this doesn't convert TO octal, it converts FROM octal. That and I wasn't calling this button anyway since I accidentally used a zero instead of an O as the symbol for the button in the program so it wasn't calling it anyway.
Part 2 was easy enough, just had to add a restriction in the function to not append when the length of the string was greater than 4 and removed the restriction on number of button presses. Since we only had <10000 states to explore I knew this would be memory safe if I coded it properly, which I did.
Did anyone else notice that the train on the calendar gets longer every time we solve a problem? I wonder how it interacts with people who choose to solve the problems out of order.
Paste
1
u/Boojum 50m ago
[LANGUAGE: Python]
The hardest part of this was just parsing the input into a set of lambdas. Python's lambda capture rules always trip me up. The rest of a straightforward Cartesian product for Part 1 and a BFS for Part 2.
1
u/PendragonDaGreat 49m ago
[Language: CSharp/C#]
code
Got completely lost in the weeds for a few minutes on part 1... because I forgot to start pressing buttons multiple times.
Part 2 was a straightforward BFS.
1
u/p88h 41m ago
[LANGUAGE: Nim]
Source: https://github.com/p88h/aoc2026/blob/main/src/day05.nim
VIdeo: https://youtu.be/eVnk8MXG_9Q
well this is basically just graph search with memoization, i.e. BFS. but looks nice.
1
u/KyleGBC 36m ago
[LANGUAGE: Rust]
Solution
Back to back easy days, I hope tomorrow is a hard one :P
1
u/Conceptizual 33m ago
[LANGUAGE: Python]
My solution involved hardcoding all the microwave buttons so my code that's committed redacted all of that. code!
I found this problem absolutely delightful, a weird thing I did was treat every microwave reading as a list of ints and then converted them to strings/numbers as needed for stuff.
1
u/onrustigescheikundig 33m ago edited 28m ago
[LANGUAGE: Scheme (R6RS)]
... with a rather large custom standard library that I've been using to play around with things like dynamic dispatch and learn about Clojure's internals.
Gitlab Day 5
Parsing (well, reading a single line): 4 μs with a bunch of noise
Part 1: 55 μs
Part 2: 11 ms
Single-line input: F E A R
In reality, not too bad, though.
After futzing around debugging my parser/combinator library (as is tradition), Part 1 came easily once I got that squared away and fixed a typo bug in the 0 case for replacing digits. It took me embarrassingly long to realize that Part 2 was just a BFS. I was fleshing out this whole bottom-up DP scheme, realized I only needed the prior iteration, and realized after that that I had just reinvented BFS with extra steps. Converting to a more proper BFS with hash sets led to my final solution.
1
u/Diamons 32m ago
[LANGUAGE: Typescriot]
https://github.com/shahruk/advent-of-code/pull/2/changes
https://adventofcode.shahruk.com/2026/day/5
Part 1 was a brute force check
Part 2 we only care about reachable nodes on a number line / actual values we can reach through a series of button presses, so when repeat visits to a number happen we no longer continue a bfs on that permutation.
1
u/aashutoshr 27m ago
[LANGUAGE: TypeScript]
https://github.com/aashutoshrathi/advent-of-code/tree/main/2026/5
https://adventofcode.shahruk.com/2026/day/5
As I read the question, I realized that Part 2 is gonna mess with the max number of pressed buttons, and it did, but still, to get the state machine and nitty-gritty right, I made Brute Force by writing 3 debuggable loops for Part 1.
For Part 2, I rewrote the main loop with a DFS for all "start eligible inputs", got stack overflow, looked again, found that eh, trees are mostly the same, added a new tracker for visited values in the tree to stop recompute, bam! works.
1
u/musifter 23m ago
[LANGUAGE: Perl]
Another fun little one. I didn't bother with a dispatch table of anonymous subs with eval... well not much, I did use it for
[*A]and[/A]buttons at the end of the if-else chain. But it was all about making code from input, so Bobby Tables is still a threat. One of the key tricks I used was throwinginton the results... it rounds down, it strips leading 0s, and it turns the empty string into a 0. All useful things for this problem.For part 1, it was tracking values in a hash and recursion to depth three, done with:
For part 2 I just changed that to:
I also needed
no warnings qw(recursion);, as this is the first time since day 12 of 2023 that I've done a recursion heavy enough to trigger the warnings.Part 1: https://pastebin.com/NkhK1Tyi
Part 2: https://pastebin.com/XtQ8fBrb
1
u/Old-Dinner4434 22m ago
[LANGUAGE: TypeScript]
GitLab
Part 1 completed in 6.12ms, and part 2 completed in 18.89ms.
1
u/ShraddhaAg 22m ago
[Language: Golang]
https://github.com/shraddhaag/aoc/blob/main/2026/day5/main.go
Designated bfsday of advent of code! got stuck in part 1 due to incorrectly implementing the `->` instruction.
1
u/ZeroTerabytes 19m ago edited 15m ago
[LANGUAGE: Rust]
Parts 1 and 2: https://pastebin.com/D5GJCQjG
For part 1, I just did a nested for loop (lol). For part 2, I actually used recursion. Most of my code is just spent parsing the input.
1
u/POGtastic 18m ago
[LANGUAGE: F#]
Code
Simple BFS problem.
I used
FParsecto parse the button strings despite this being a little bit overkill. I hate regexes, (regices?) and parser combinators offer the ability to write individual parsers for each case and then combine them. It's easier to organize and works better with F#'s type theory nonsense [laudatory] than regexes.BFS in F# is a simple unfold operation. I keep two arguments: an accumulator to remove numbers that have already been encountered, and a set of active numbers. Generate a new set of numbers and remove the ones that have already been seen. If the result is empty, we're done. Otherwise, the active numbers are the result, and the accumulator is now the union of the accumulator and the result. All of this works very nicely with F#'s
Setlibrary.Part 1 is just
Seq.take 3on this unfold, followed by aunionMany. Part 2 omits theSeq.take 3.1
u/Fuzzy_Patterns 14m ago
[LANGUAGE: Nim]
Part1: bruteforce
Part2: recursive DFS with hashset, so we don't repeat states.
Solution on Codeberg: solution.nim
1
u/sim642 12m ago
[LANGUAGE: Scala]
On GitHub.
Mostly just calling my BFS library: in part 1 with target distance 3, in part 2 with full traversal but filtering out too long numbers. So part 2 was just a minor modification. I feared much worse though.
1
u/janek37 11m ago
[LANGUAGE: Rust]
https://github.com/janek37/advent-of-code/blob/main/2026/day05.rs
1
u/FruitdealerF 9m ago
[LANGUAGE: Andy C++]
Cute puzzle, I wrote out my input as a set of functions and did a simple BFS and got the answer quite quickly. Then I tried to rewrite it to DFS, broke my brain and gave up.
github
1
u/light_ln2 6m ago
[LANGUAGE: Python]
This one was very hard to write short! I could squeeze it in 7 lines but it became completely unreadable unfortunately. Looking forward to see how other approaches balance between brevity and readability!
1
u/Pyr0Byt3 6m ago
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2026/05/1.go
I love BFS.