r/adventofcode • • 1d ago

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

THE USUAL REMINDERS


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 date finer the vintage, the more we'll enjoy it!

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.

22 Upvotes

425 comments sorted by

5

u/tymscar 1d ago edited 20h ago

[LANGUAGE: Racket]

Day 5 in racket. I loved it. Super cool problem, super fun solution, 10/10.

Some things I found strange about racket. The way it prints stuff in the repl. It usually prints it with the constructor, such as (set 1 2 3) but for historical lisp stuff like lists instead of (list 1 2 3) it does '(1 2 3), but it's non consistent. If you have a set in a list, it uses constructor for both because otherwise ' wouldnt work there.

Another weird thing is set-equal? despite the name and despite the question mark it doesnt tell you if two sets are equal, it tells you if the values inside are compared with equal. Ugh. What you want there instead is set=?.

This last bit was a bit annoying but failures often return false isntead of an error. For example string->number. So you end up having to debug and go through them one by one until you find it, instead of getting an error that says exactly what failed to be converted.

For part1 I initially thought about repeating every button 3 times and use a combinations call to give me every combination of buttons and just make it. I realised this is part 1 and that is not gonna fly for part 2 for sure (thinking part2 will want me to run 20 buttons or something) so I thought about it a bit more and realised its a simple BFS problem. So I added a depth counter and when I am at depth 3 I stop, otherwise I calculate all the new values by applying the button presses and pass it on.

For part2 it was easier than I thought and it basically said to stop once no new values were created. That was easy. I changed my apply function to only apply the button press if the value created is equal to or lower than 9999 (biggest 4 digit value) got rid of the depth idea, and just ran it until the new set was equal with the old one, at which point I would start returning from the recursion.

Part1 and Part2

2

u/daggerdragon 1d ago edited 20h ago

Psst: Your Markdown is broken because the backticks are getting escaped by the fancypants editor. Fix please? edit: 👍

→ More replies (1)

4

u/WilkoTom 1d ago edited 1d ago

[LANGUAGE: Rust] [ALLEZ CUISINE!] [Advent Games]

Solution

Apparently today is my Cake Day. And as u/topaz2078 has been so kind as to give me a fancy microwave for the occasion, there was only one recipe I could possibly share:

Advent of Cookery Encore Encore: Chocolate Microwave Mug Cake

→ More replies (2)

4

u/badpinkshark 1d ago edited 19h ago

[LANGUAGE: TypeScript]

I think for part 1, my instincts were to use Cartesian product cumulatively for all buttons. Basically generate all possible button combinations for 1-3 times and then run through the button combinations into a function that processes the instructions and whatnot. I know that we only need to generate for 1-3 possible button combinations but I created a general function for it and its also recursive.

Until part 2 came… I didn’t really understand why a BFS is needed and how it is represented until I saw a visualisation on this subreddit and it made sense. It’s also my first ever time doing a graph traversal problem. I guess I understand BFS partly now…

[Solution]

→ More replies (3)

3

u/DFreiberg 1d 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[] and Hold[] options. And it still doesn't completely work; I eventually decided to solve the error message it gave me by wrapping the offending line in Quiet[], so that I don't have to look at the error anymore.

Setup:

input = StringReplace[Import[inputPath], "[" | "]"];
parseButton[button_String] :=
  First@StringCases[button,
    {"*" ~~ x : DigitCharacter .. :> num*ToExpression[x],
     "/" ~~ x : DigitCharacter .. :> Quotient[num, ToExpression[x]],
     x : DigitCharacter .. ~~ "->" ~~ y : DigitCharacter .. :> (Hold[FromDigits[IntegerDigits[num, 10] /. #]] &@{ToExpression[x] -> ToExpression[y]}),
     "oct" :> FromDigits[IntegerDigits[num, 8], 10],
     "bksp" :> Quotient[num, 10],
     x : DigitCharacter .. :> num*10 + ToExpression[x]}];
heldButtons = Quiet@Join[Flatten[parseButton /@ input], {num}];
operations[n_] := Block[{num = n}, ReleaseHold[heldButtons]];

Part 1:

Total[Nest[Union[Flatten[operations[#] & /@ #]] &, {0}, 3]]

Part 2:

Total[FixedPoint[Union[Flatten[(operations[#] /. x_?(# > 9999 &) :> Nothing) & /@ #]] &, {0}]]

2

u/daggerdragon 1d ago

!!! Our resident Poet Laureate is here! Hi and welcome back this year! <3

→ More replies (1)

2

u/flwyd 1d ago

[LANGUAGE: R] (on GitHub)

Alright, a string parsing problem! After a couple days of stumbling around with multi-dimensional arrays, I’m excited to be in my usual kitchen: string (cheese) manipulation. (Sorry mods, that’s the most advent games I’ll do this evening.)

A couple days ago I was scratching my head about why R didn’t have a hash map in the standard library. Today I realized the data type R calls a list looks a lot like a hash map, or like that freaky PHP hybrid integer/map array hybrid. An R list works a lot like a vector, but it’s got named fields in addition to numeric fields. My implementation keeps everything in the string domain, converting back and forth from integers as necessary. It does absolutely nothing algorithmicly fancy and takes 5.5 seconds to find 8040 reachable numbers on the example input and 8 seconds to find 8591 reachable numbers on my actual input. As I was writing this comment, I realized that’s suspiciously slow for that many results, and that list probably does not have the O(1) amortized insert performance of a real hash map. Sure enough, switching to an all-integers implementation (at the GitHub link above) drops it to roughly half a second.

In addition to “list string key lookups are apparently linear,” other things I learned about R today:

  • Integer objects can have attributes, including the octmode attribute which prints the number in octal. At an R prompt, if you type as.octmode(1:63) the REPL will show you strings 01…07…10…17…70…77. This is sticky, too: as.octmode(1:63) * 2 gives 002…176.
  • I’m very glad that R treats strings as atomic objects. Most of the array languages in the APL family treat an array of strings as a 2D array of characters and get fussy if the strings have different lengths.
  • I’m still trying to understand how negative indices work in R. They do… something with arrays, but it’s not “index from the end” like Python and some other languages do. And substr(x, 2, -1) gives an empty string, so I had to fall back to the aesthetically pleasing regular expression [][] (that’s a [chars] expression where the first character is ] and the second one is [, not two adjacent empty sets).
  • I’m really enjoying the which function. The expression sum(which(reachable)) (add the array indices where the array value is true) is really slick, and my day 4 solution made good use of which. for (n in which(reachable)) is just as nice as the for (n in reachable.keys()) idiom I would’ve used in a language with a hash map. I’m glad I picked that up from folks in the Day 2 megathread.

Code:

part1 <- function(lines) {
  words <- strsplit(lines[1], " ")[[1]]
  buttons <- lapply(gsub("[][]", "", words), parse_button)
  reachable <- list("0" = TRUE)
  for (step in 1:3) {
    for (n in names(reachable)) {
      for (b in buttons) { reachable[[b(n)]] <- TRUE }
    }
  }
  names(reachable) |> as.integer() |> sum()
}
part2 <- function(lines) {
  words <- strsplit(lines[1], " ")[[1]]
  buttons <- lapply(gsub("[][]", "", words), parse_button)
  reachable <- list("0" = TRUE)
  repeat {
    changes <- 0
    for (n in names(reachable)) {
      for (b in buttons) {
        v <- b(n); if (nchar(v) > 4) { next }
        if (is.null(reachable[[v]])) {
          reachable[[v]] <- TRUE
          changes <- changes + 1
        }
      }
    }
    if (changes == 0) {
      return(names(reachable) |> as.integer() |> sum())
    }
  }
}
parse_button <- function(b) {
  if (b == "oct") {
    format.octmode
  } else if (b == "bksp") {
    \(s) if (nchar(s) == 1) "0" else substr(s, 1, nchar(s) - 1)
  } else if (startsWith(b, "*")) {
    digit <- as.integer(substr(b, 2, 3))
    \(s) as.character(as.integer(s) * digit)
  } else if (startsWith(b, "/")) {
    digit <- as.integer(substr(b, 2, 3))
    \(s) as.character(floor(as.integer(s) / digit))
  } else if (grepl("->", b)) {
    from <- as.integer(substr(b, 1, 1))
    to <- as.integer(substr(b, 4, 4))
    \(s) gsub(from, to, s)
  } else {
    \(s) if (s == 0) b else paste0(s, b)
  }
}
→ More replies (3)

2

u/RazarTuk 1d ago edited 1d ago

[LANGUAGE: Kotlin]

paste


[Advent Games]

Cookies! Okay, so last year I made more cookies than I knew what to do with and brought some to work because I could. This year I'm doing that on purpose. In order, a truly disturbing amount of confectioner's sugar, a truly disturbing amount of cake flour, the partially finished dough (8 eggs, 1 kg confectioner's sugar, 2 t anise extract, 1/2 t salt, and 1/2 t baker's ammonia), a 5-lb puck of dough, the rolled and cut cookies ready to dry (yes, one of the steps is letting them sit out on the counter for 24 hours), and the start of a different recipe, where I melted butter, cream, brown sugar, molasses, and honey together.

But yeah, the dough's mostly just eggs, powdered sugar, and cake flour, notably without any sort of butter, and it produces a cakier cookie. The drying step essentially sets the images by preventing it from rising up as much. And instead, a lot of the expansion happens downward, producing a characteristic foot that might give the cookies their name. They're called springerle in German, which roughly means something like "little springers"

EDIT: Ugh. I thought I was being creative and saving space by using a fancy rack, but the bottoms also dried out, ruining the batch

→ More replies (2)

2

u/Busy-Contact-5133 1d ago

1

u/daggerdragon 1d ago edited 32m ago

Do not share your puzzle input which also means do not commit puzzle inputs to your repo without a .gitignore or the like. Do not share the puzzle text either.

I see full plaintext puzzle inputs and puzzle text in your public repo e.g.:

https://github.com/dawit909/aoc/blob/main/d03/input.txt https://github.com/dawit909/aoc/blob/main/d05/descriptions.txt

Please remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history. This means from all prior years too! edit: 👍

2

u/Busy-Contact-5133 9h ago

Not sure if my comment is removed, but i removed inputs and descriptions from my repo. So un-remove my comment. Thank you.

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

2

u/sheshanaag 1d ago edited 1d ago

[LANGUAGE: Haskell]

Both parts

Main module

→ More replies (2)

2

u/acquitelol 1d ago edited 23h ago

[LANGUAGE: Elle]

use std/prelude;
use ../aoc;

namespace day05;
global pub;

enum Op { Affine, Div, Rep, Oct }

fn day05::parse(char[] line) {
    buttons := Array::with_capacity<(Op, u64, u64)>(line.len());

    for b in line.split_iter([' ']).map(fn: it.slice(1, -1)) {
        if (_, parsed) := u64::maybe_parse(b.elements) {
            buttons.push((Op::Affine, 10u64, parsed));
        } else if b[0] == '*' || b[0] == '/' {
            v := u64::parse(b.slice_from(1).elements);
            buttons.push((b[0] == '*' ? Op::Affine : Op::Div, v, 0u64));
        } else if b.elements == "bksp" {
            buttons.push((Op::Div, 10u64, 0u64));
        } else if b.elements == "oct" {
            buttons.push((Op::Oct, 0u64, 0u64));
        } else if b.contains('-') {
            buttons.push((Op::Rep, #cast(u64, b[0] - '0'), #cast(u64, b[3] - '0')));
        }
    }
    
    return buttons;
}

fn day05::press(u64 n, (Op, u64, u64) button) -> u64 {
    (op, a, b) := button;
    if op == Op::Affine { return n * a + b; }
    if op == Op::Div { return n / a; }
    if n == 0 { return op == Op::Rep && a == 0 ? b : 0; }
    return op == Op::Oct ? n.to_base(8) : n.replace(a, b);
}

fn day05::solve(char[] line) {
    buttons := day05::parse(line);
    total: u64[2] = std::filled();

    dist: u64[10_000] = std::filled();
    dist[0] = 1;
    
    queue := Deque::new<u64>();
    queue.push_back(0u64);

    while (_, n) := queue.pop_front() {
        total[1] += n;
        total[0] += dist[n] <= 4 ? n : 0;

        for button in buttons {
            v := day05::press(n, button);
            if v < 10_000 && dist[v] == 0 {
                dist[v] = dist[n] + 1;
                queue.push_back(v);
            }
        }
    }
    return total;
}

fn day05::main() -> Day {
    return Day::stc(day05::solve(#embed_slice("input.txt").split_iter(['\n']).next()!));
}

Runs in:

------------------------------
Day 5 ran in 2978.076141us (1000 attempts)
Day 5: Day::static([17893, 45651060])
------------------------------

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

2

u/daggerdragon 1d ago

Your code block is too long for the megathreads. You already have a link to the code in your repo so please delete or vastly shorten the code block.

9

u/4HbQ 1d ago edited 1d ago

[LANGUAGE: Python] 15 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:

match button:
    case A,:     return display * 10 + int(A)
    case '*',A:  return display * int(A)
    case '/',A:  return display // int(A)
    ...
→ More replies (6)

9

u/ThunderChaser 1d ago

[LANGUAGE: Prolog]

Having written a very disgusting solution in Rust, I realized that today's problem is an almost textbook application of logic programming.

We're computing reachability over a finite state space, which lends itself beautifully to tabled evaluation in Prolog. The rest of the implementation is calculator semantics and a definite clause grammar (DCG) for parsing the input.

paste

→ More replies (2)

8

u/siener 1d ago edited 1d ago

[LANGUAGE: Dyalog APL]

  • This is the first time I've ever used ⍣ and it's awesome, especially in part 2 where ⍣≡ gives you the function fixed point.
  • I added the identity function (i.e. [*1]) to my input, but I still get the correct answer without it. I suspect that won't always be the case for all possible inputs, but I'm not sure
  • The parsing logic is flimsy as hell, but it works for my input. The example in the problem statement uses a two digit number for [A], which won't work. It's easy to fix, but I'm too lazy
d←(⊂'*1'),(∊∘' []'~⍛⊆⊢)⊃⊃⎕NGET'05.txt'1
f←{
     1=≢⍺:(⍎⍺)+⍵×10
     '*'=⊃⍺:⍵×⍎⍺[2]
     '/'=⊃⍺:⌊⍵÷⍎⍺[2]
     'oct'≡⍺:10⊥⍵⊤⍨8⍴⍨⌈8⍟⍵+1
     'bksp'≡⍺:⌊⍵÷10
     ⍎(4⊃⍺)@(=∘(1⊃⍺))⊢⍕ ⊢ ⍵
}
clamp←{t←⍺ f ⍵ ⋄ 4<⌈10⍟t+1:⍵ ⋄ t}
apply←{⊂⍤⍋⍛⌷∪,⍺∘.clamp ⍵}
+/¨d((apply⍣3),⍥⊂(apply⍣≡))0 ⍝ Part 1 & 2
→ More replies (4)

6

u/michelkraemer 1d 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 and value.replace(a, b) to replace digit a with b in the string. I then cleaned up the code and replaced the strings with usize.

Finally, I removed the HashSet I initially used to avoid visiting numbers again and replaced it with a simple Vec<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.

→ More replies (3)

5

u/imperfect-fourth 1d ago

[LANGUAGE: Nix]

Day 5

hopefully the difficulty picks up soon

5

u/lunar_mycroft 1d ago edited 1d ago

[LANGUAGE: rust]

Spent an embarrassing amount of time trying to use the wrong combinatoric iterator, ended up abandoning that approach all together in the end.

Full code. Both parts use the same basic technique: take a HashSet of the starting numbers, apply each of the instructions too it, and merge the results back in. For part 1 this is just repeated three times. For part 2 I instead loop until there's no new numbers to add. Parsing is very fast (not surprising given how short the input is) at 1µs, part 1 takes 5.338µs, and part 2 take 5.407ms.


Refactored to move the common logic into lib.rs. Runtimes unchanged.


I think my initial (bad) plan to treat the problem like an instruction set completely threw me off, because I didn't think to use a proper BFS until checking the thread (specifically /u/maneatingape's solution). This speeds part 2 up to ~260µs, but in my testing it was if anything slightly slower for part 1. One minor potential improvement I was able to make was to keep track of the sum as I was doing the search, rather than summing after.


Using an array instead of a HashSet for part 1 (credit to /u/michelkraemer via /u/maneatingape for pointing out that the problem was suitable for that) speeds it up to ~1.9µs.

→ More replies (2)

5

u/tqzd 1d ago edited 18h ago

[LANGUAGE: Excel]

Part 1 & 2

=LET(
   b, TEXTSPLIT(A1," "),
   o, IFNA(REGEXEXTRACT(b, "[*/>ob]"),),
   n, REGEXEXTRACT(b, "\d"),
   M, LAMBDA(v, LET(
     r, --IF(o="*",v*n,IF(o="/",INT(v/n),
            IF(o=">",SUBSTITUTE(v,n,MID(b,5,1)),
              IF(o="o",BASE(v,8),IF(o="b",INT(v/10),v&n)))
     )),
     IF(r<10000,r,v)
  )),
  MAP({3;15},LAMBDA(i,
    SUM(REDUCE(0,SEQUENCE(i),LAMBDA(v,_,UNIQUE(VSTACK(v,TOCOL(M(v),3))))))
  ))
)

5

u/Foldzilla 1d ago

[LANGUAGE: Haskell]

I like my solution it sees button as a long chain of functions that convert a display (Int) to a new display with a function. This allows me for part one to define a Monoid and Semigroup instance using function composition and identity, which I use to collapse each sequence of button presses. This day I could finally test my own parser combinator library a bit, and it seems to do fine. replicateM makes the sequences of button trivial. For part 2 I just implemented BFS on the unique numbers. Here I could not take advantage of my button as functions approach. Hope you guys can appreciate the code! :).

https://github.com/JustinKasteleijn/AOC2026/blob/main/app/Day5/Day5.hs

4

u/jonathan_paulson 1d 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!

4

u/DBSmiley 1d ago edited 1d ago

[Language: Kotlin]

Solution

Wanted to "over-design" the solution a bit just to play with Kotlin sealed interface.

sealed interface Button  {
    data class Digit(val digit: Int): Button
    data class Multiply(val operand: Int): Button
    data class Divide(val operand: Int): Button
    data class Swap(val originalDigit: Int, val newDigit: Int): Button
    object Octal: Button
    object BackSpace: Button
    
    fun press(state: Int): Int =
        when(this) {
            is Digit -> state * 10 + this.digit
            is Multiply -> state * this.operand
            is Divide -> state / this.operand
            is Swap -> executeSwap(state, this.originalDigit, this.newDigit)
            is Octal -> convertToOctal(state)
            is BackSpace -> state / 10
        }
}

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).

fun getPart2Result(buttons: List<Button>): Long {
    val stack = Stack<Int>()
    val visited = mutableSetOf<Int>()
    stack.add(0)
    while (stack.isNotEmpty()) {
        val node = stack.pop()
        buttons.forEach { button ->
            val next = button.press(node)
            if (next <= 9999 && !visited.contains(next)) {
                visited.add(next)
                stack.push(next)
            }
        }
    }
    return visited.sumOf { it.toLong() }
}

Since a lot of people are posting their button-parsing, here's mine. Why be clever when I can just be simple:

fun toButton(string: String): Button {
    val buttonText = string.substring(1..<string.lastIndex)
    if (buttonText == "oct") { return Button.Octal }
    if (buttonText == "bksp") { return Button.BackSpace }
    if (buttonText.length == 1) { return Button.Digit(buttonText.toInt()) }
    if (buttonText.startsWith("*")) { return Button.Multiply(buttonText[1].digitToInt()) }
    if (buttonText.startsWith("/")) { return Button.Divide(buttonText[1].digitToInt()) }
    if (buttonText.contains("->")) { return Button.Swap(buttonText[0].digitToInt(), buttonText[3].digitToInt()) }
    throw IllegalStateException("Back input: $buttonText")
}
→ More replies (1)

4

u/POGtastic 1d ago

[LANGUAGE: F#]

Code

Simple BFS problem.

I used FParsec to 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 Set library.

Part 1 is just Seq.take 3 on this unfold, followed by a unionMany. Part 2 omits the Seq.take 3.

4

u/encse 1d ago

[LANGUAGE: C#]

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

ehh, why not

    Button button = part switch {
        "oct" => Oct(),
        "bksp" => Div(10),
        _ when part.StartsWith("*") => Mul(arg),
        _ when part.StartsWith("/") => Div(arg),
        _ when part.Split("->") is [var a, var b] => Replace(a, b),
        _ => Const(arg),
    };
→ More replies (2)

4

u/Outrageous72 1d ago

[LANGUAGE: C#]

It was easier than I thought at first.

The memory usage was high at first but I changed the impl of octal and replace buttons to not use strings.

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

int Part2(string line)
{
    var buttons = ParseButtons(line);
    var results = new HashSet<int>();

    foreach (var button in buttons) results.Add(button.Push(0));

    while (true)
    {
        var countBefore = results.Count;

        foreach (var input in results.ToArray())
        {
            foreach (var button in buttons)
            {
                var result = button.Push(input);
                if (result < 10000) results.Add(result);
            }
        }

        if (results.Count == countBefore) break;
    }

    return results.Sum();
}

4

u/Ok-Bus4754 1d ago

[Language: Python + Rust]

another easy day, was expecting harder, this year is easier than 2025 , expcting/hoping for a dificult one tomorrow

straight forward bfs while keeping track of seen number and changing the condition for part 1 and 2, steps vs limit

https://github.com/Fadi88/AoC/blob/master/2026/days/day05/src/lib.rs
https://github.com/Fadi88/AoC/blob/master/2026/days/day05/solution.py

Python 3.15Rust debugRust release
Part 122.9 us107.8 us9.37 us
Part 28.66 ms21.9 ms2.80 ms

4

u/jhandros 1d ago

[LANGUAGE: Excel]

=LET(o,TOCOL(TEXTSPLIT(SUBSTITUTE(SUBSTITUTE(A1,"[",""),"]","")," "),1),c,LAMBDA(r,x,IF(LEFT(r)="*",x*--MID(r,2,99),IF(LEFT(r)="/",QUOTIENT(x,--MID(r,2,99)),IF(ISNUMBER(SEARCH("->",r)),--SUBSTITUTE(x&"",TEXTBEFORE(r,"->"),TEXTAFTER(r,"->")),IF(r="oct",--DEC2OCT(x),IF(r="bksp",QUOTIENT(x,10),10*x+--r)))))),a,LAMBDA(v,LET(n,ROWS(v),m,ROWS(o),MAKEARRAY(n*m,1,LAMBDA(i,j,c(INDEX(o,MOD(i-1,m)+1),INDEX(v,ROUNDUP(i/m,0))))))),z,REDUCE(0,SEQUENCE(3),LAMBDA(v,k,UNIQUE(VSTACK(v,a(v))))),p,LET(x,a(0),UNIQUE(FILTER(x,x<=9999))),w,LAMBDA(s,q,p,LET(x,a(p),v,(x<=9999)*ISNA(XMATCH(x,q)),IF(SUM(--v)=0,q,LET(n,UNIQUE(FILTER(x,v)),s(s,VSTACK(q,n),n))))),q,w(w,p,p),HSTACK(SUM(z),SUM(q)))

→ More replies (2)

4

u/ednl 1d ago edited 21h ago

[Language: C]

Same as many already posted: 2x BFS, part 1 with depth restriction. Not fully optimised yet e.g. I should probably replace the boolean seen arrays with a bitset. Runtimes: M4 163 µs, M1 283 µs, Pi5 475 µs. EDIT: bitset was slower. But I removed one test from the enqueue check, one branch each from rep() and oct(). New runtimes: M4 127 µs, M1 223 µs, Pi5 456 µs. EDIT2: I made the "circular" queue an array where head and tail only go forward, including branchless inserting. Space-wise that's incredibly wasteful so probably not a good option for the Pico of /u/DelightfulCodeWeasel . New runtimes: M4 102 µs, M1 175 µs, Pi5 437 µs.

EDIT3: Alrighty then. I borrowed maneatingape's replace function (and the idea of pre-calculating all possible transitions) and that did it: I got about the same time. I'm still missing something here or there because my M4 should be a little faster than Ape's M3. Could also be Rust's more modern optimisations compared to the relatively old Apple clang on my machine. New runtimes: M4 85 µs, M1 142 µs, Pi5 329 µs. This code is now gone:

static unsigned press(const unsigned x, const Btn btn)
{
    switch (btn.fun) {
        case NOP: return x;
        case ADD: return x * 10 + btn.a;
        case MUL: return x * btn.a;
        case DIV: return x / btn.a;
        case REP: return rep(x, btn);
        case OCT: return oct(x);
        case BCK: return x / 10;
    }
    __builtin_unreachable();
}

https://github.com/ednl/adventofcode/blob/main/2026/05.c

→ More replies (7)

4

u/Snoopy34 1d ago

[Language: Rust]

I also first did this with the brute force approach with the cartesian product and then got hit on the head when it asked for unlimited number of button presses so had to resort to the good old BFS. And also I was so confused with the replacement operation for some reason I thought that it should replace with a second operand no matter what if the current result is 0 and what's weird is that the test input was getting the right result with that approach, but that's totally what I get for not reading the instructions properly. Other than that, pretty cool puzzle.

code (topaz paste)

4

u/Gabba333 1d ago

[LANGUAGE: C#]

Keep pressing buttons on the set of numbers reached so far until this set stops growing. Not the most efficient as we are generating unnecessary duplicates but plenty fast enough. For my input 13 rounds of button presses is enough.

var buttons = File.ReadAllText("input.txt").Trim('[', ']').Split("] [");
HashSet<string> all = ["0"];
int curr = 1, count = 0;
do
{
    curr = all.Count;
    all.UnionWith([.. all.SelectMany(c => buttons.Select( b => b switch {
        [var d]                     => (c == "0" ? "" : c) + d,
        ['*', var d]                => (int.Parse(c) * (d - '0')) + "",
        ['/', var d]                => (int.Parse(c) / (d - '0')) + "",
        [var d1, .. "->", var d2]   => c.Replace(d1, d2),
        "oct"                       => Convert.ToString(int.Parse(c), 8),
        "bksp"                      => c.Length == 1 ? "0" : c[..^1],
    } switch { var n => n.Length > 4 ? c : n }))]);

    if (++count == 3) Console.WriteLine(all.Sum(int.Parse));
}
while (all.Count > curr);
Console.WriteLine(all.Sum(int.Parse));
→ More replies (3)

4

u/Langston723 23h ago

[LANGUAGE: Lua]

Example operations (used in Part 1 & 2)

Part 1 (permutations with repetition)

Part 2 (BFS)

I spent a fair amount of time thinking about how to create buttons programmatically from the input txt. Then I looked at my real input file and decided to hard code it.

4

u/soolpro 22h ago

[Language: Python]

It's easier for me to name variables and functions in my native language so here I go again. I love the set data structure in puzzles like these.

Part 1:

import itertools


with open("input.txt") as f:
    napit = f.readline().strip()[1:-1].split("] [")


def paina(luku: int, nappi: str) -> int:
    if "*" in nappi:
        return int(nappi[1:]) * luku
    elif "/" in nappi:
        return luku // int(nappi[1:])
    elif "->" in nappi:
        muutos = [nro for nro in nappi.split("->")]
        if muutos[0] in str(luku):
            return int(str(luku).replace(muutos[0], muutos[1]))
        else:
            return luku
    elif nappi == "oct":
        return int(oct(luku)[2:])
    elif nappi == "bksp":
        return luku // 10
    else:
        return luku * 10 + int(nappi)


tulokset = set()
for painallukset in itertools.product(napit, repeat=3):
    luku = 0
    for nappi in painallukset:
        luku = paina(luku, nappi)
    tulokset.add(luku)


print(f"Kaikkien mahdollisten aikojen summa on {sum(tulokset)}")

Part 2:

with open("input.txt") as f:
    napit = f.readline().strip()[1:-1].split("] [")


def paina(luku: int, nappi: str) -> int:
    if "*" in nappi:
        palautettava = int(nappi[1:]) * luku
    elif "/" in nappi:
        palautettava = luku // int(nappi[1:])
    elif "->" in nappi:
        muutos = [nro for nro in nappi.split("->")]
        if muutos[0] in str(luku):
            palautettava = int(str(luku).replace(muutos[0], muutos[1]))
        else:
            palautettava = luku
    elif nappi == "oct":
        palautettava = int(oct(luku)[2:])
    elif nappi == "bksp":
        palautettava = luku // 10
    else:
        palautettava = luku * 10 + int(nappi)
    if palautettava < 10000:
        return palautettava
    else:
        return luku


kokeiltavat = {0}
kalutut = set()
tulokset = set()
uudet = {0}


while len(uudet) > 0:
    uudet = set()
    for luku in kokeiltavat:
        for nappi in napit:
            tulos = paina(luku, nappi)
            if tulos not in tulokset:
                tulokset.add(tulos)
                uudet.add(tulos)
    kokeiltavat = uudet


print(f"Kaikkien mahdollisten tulosten summa on {sum(tulokset)}")

4

u/terje_wiig_mathisen 21h ago edited 14h ago

[LANGUAGE: Perl + Rust]

This was another natural for Perl, mixing numbers and text_as_numbers is core to the language. That version runs in about 90 ms, the press function does the key presses:

sub press
{
  my ($disp, $b) = @_; # current display, button to press
  if ($b eq '[oct]') { return sprintf("%o",$disp); }
  if ($b =~ /\[(\d)\-\>(\d)\]/) { 
    my ($f, $t) = ($1, $2);
    $disp =~ s/\Q$f\E/$t/g;
    return $disp;
  }
  if ($b =~ /\[\*(\d)\]/) { return $disp * $1; }
  if ($b =~ /\[\/(\d)\]/) { return int($disp / $1); }
  if ($b =~ /\[(\d)\]/) { return ($disp.$1)*1; } # mul by 1 in case we started with a zero!
  if ($b eq '[bksp]') { return int($disp/10); }
  die("unknown button $b");
}

For Rust I started by replicating all of this using the regex crate, but found that it was both cumbersome and slow so I reverted to explicitly parsing out the digits from the button alternatives in my input.

I could have made it a lot faster if I hardcoded the button list, but that seems to much like cheating so I kept the loop iterating over the buttons. The only pre-processing was to remove the [] brackets around each button.

I use a reach vec![u8::MAX;10000] to mark each number with the number of keys hit so far to find it, then I push it onto VecDeque which keeps going until there are no more untried numbers.

For the actual processing I wrote a custom [oct] conversion, as well as the [n->m] buttons.

It was 4 x slower than u/maneatingape, but when I checked again just now, his code has gotten more than twice as fast so now I'm an order of magnitude behind! Is there a way to directly determine which numbers are unreachable based on the button inputs?

1

u/aquinas_nz 1d ago

[Language: F#]

type Button = 
    | Number of int
    | Multiply of int
    | Divide of int
    | Replace of int * int
    | Oct
    | Backspace


let parse = System.Int32.Parse

let buttons = 
    data.Split (" []".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries)
    |> Array.map (fun s -> 
        if s = "oct" then Oct
        else if s = "bksp" then Backspace
        else if s[0] = '*' then Multiply (parse s[1..])
        else if s[0] = '/' then Divide (parse s[1..])
        else if s.Contains "->" then
            let parts = s.Split "->"
            Replace (parse parts[0], parse parts[1])
        else
            Number (parse s))

let apply button number =
    match button, number with
    | Number a, 0 -> a
    | Number a, n -> let s = n.ToString() in parse (s + a.ToString())
    | Replace (a, b), n -> let s = n.ToString() in s.Replace(a.ToString(), b.ToString()) |> parse
    | _, 0 -> 0
    | Multiply a, n -> a * n
    | Divide a, n -> floor (float n / float a) |> int
    | Oct, n -> parse (System.Convert.ToString(n, 8))
    | Backspace, n when n < 10 -> 0
    | Backspace, n -> let s = n.ToString() in parse (s[0..s.Length-2])
    
// Gate for part 2 that doesnt affect part 1
    |> fun n -> if n > 9999 then number else n

// Part 1
buttons |> Seq.collect (fun a -> 
    buttons |> Seq.collect (fun b -> 
        buttons |> Seq.map (fun c -> 
            (a, b, c))))
        |> Seq.distinct
        |> Seq.map (fun (a, b, c) -> 0 |> apply a |> apply b |> apply c)
        |> Seq.distinct
        |> Seq.sum
        |> printfn "%i"

// Part 2
let rec search found accs =
    let next = accs |> Array.collect (fun acc -> buttons |> Array.map (fun b -> apply b acc) |> Array.filter (fun n -> not (Set.contains n found)))
    if next.Length = 0 then found
    else
        let newFound = Set.union found (Set.ofSeq next)
        search newFound next
search Set.empty [|0|] |> Seq.sum |> printfn "%i"

1

u/daggerdragon 1d ago

Your code block is too long for the megathreads. Edit your comment to replace your oversized code with an external link to your code.

1

u/blackhat-hemsworth 22h ago edited 22h ago

[Language: Haskell]

I am definitely re-running some computations here but I think haskell is very clean for this sort of thing (change sign to run pt 1)

module Main where

import System.Environment (getArgs)
import Text.Printf (printf)
import Data.List.Split (splitOn)
import qualified Data.Set as Set

append :: Int -> (Int -> Int)
append a b = read (show b ++ show a) :: Int

multiply :: Int -> (Int -> Int)
multiply a = (*a)

divide :: Int -> (Int -> Int)
divide a b = div b a

replace :: [Int] -> (Int -> Int)
replace [a, b] s = read (map (\c -> if c == head (show a) then head (show b) else c) (show s)) :: Int -- two digits...?
replace _ _ = error "bad input, list needs to have two integers"

octalize :: (Int -> Int)
octalize i = read (printf "%o" i) :: Int

backspace :: (Int -> Int)
backspace i
  | i > 10 = read (init (show i)) :: Int
  | otherwise = 0

safe :: Int -> (Int -> Int) -> Int
safe n op = if op n <= 9999 then op n else n

getOp :: String -> (Int -> Int)
getOp s
  | s == "oct" = octalize
  | s == "bksp" = backspace
  | '>' `elem` s = replace (map (\st -> read st :: Int) (splitOn "->" s))
  | '/' `elem` s = divide (read (tail s) :: Int)
  | '*' `elem` s = multiply (read (tail s) :: Int)
  | otherwise = append (read s :: Int)

runOps :: Set.Set Int -> [Int -> Int] -> Int -> Set.Set Int
runOps set _ 0 = set
runOps set ops n
  | _hSet set ops Set.\\ set == Set.empty = set
  | otherwise = runOps (set <> _hSet set ops) ops (n+1)
  where _hSet s o = Set.fromList [safe e op | op <- o, e <- Set.toList s ]

solveLines :: [String] -> Int
solveLines ls = sum (runOps (Set.fromList [0]) (map (getOp . init . tail) ls) 3)

main :: IO ()
main = do
  args <- getArgs
  let path = case args of
        (p : _) -> p
        [] -> "2026/day05/input.txt"
  contents <- readFile path
  let ls = words contents

  putStrLn ("total: " ++ show (solveLines ls))

2

u/daggerdragon 14h ago

Your code block is too long for the megathreads. Edit your comment to replace your oversized code with an external link to your code, please.

3

u/Kermitnirmit 1d 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/AYM123 1d 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

→ More replies (1)

3

u/FCBStar-of-the-South 1d ago edited 1d 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

3

u/xelf 1d ago edited 1d ago

[LANGUAGE: Python]

def press(n,a):
    match a[0]:
        case '*': return int(n) * int(a[1])
        case '/': return int(n) // int(a[1])
        case 'o': return int(f"{n:o}")
        case 'b': return n//10
    if "->" in a: return int(str(n).replace(*a.split("->")))
    return n*10+int(a)

old, result, buttons = 0, {0}, re.findall(r"\[([^\]]*)\]",  open(filename).read())
while len(result) > old:
    old = len(result)
    result |= {z for k,a in product(result, buttons) if int(z:=press(k,a))<=9999}
print(sum(result))

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:

ops = {
    '*': lambda n,a: int(n) * int(a[1]),
    '/': lambda n,a: int(n) // int(a[1]),
    'o': lambda n,a: int(f"{n:o}"),
    'b': lambda n,a: n//10,
    '-': lambda n,a: int(str(n).replace(*a[1:].split("->"))),
    'd': lambda n,a: n*10+int(a[1]),
}

todo, result, buttons = {0}, set(), re.findall(r"\[([^\]]*)\]",  open(filename).read())
while todo:
    todo = {z for k,a in product(todo, buttons) if (z:=ops[a[0]](k,a))<=9999} - result
    result |= todo
print(sum(result))

Here I edited my input to add the '-' and 'd'

→ More replies (7)

3

u/p88h 1d 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.

          parse    part1    part2    total
day 05:  0.32 µs  1.67 µs  0.12 ms  0.13 ms (±1.3%)

3

u/onrustigescheikundig 1d ago edited 1d 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: 33 μs

Part 2: 8.6 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 and that I should probably implement Part 1 that way, too. 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.

3

u/musifter 1d 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 throwing int on 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:

    $values{$new}++;
    &recurse( $new, $depth + 1 )  if ($depth < 3);

For part 2 I just changed that to:

    if ($new <= 9999 and !$values{$new}) {
        $values{$new}++;
        &recurse( $new );
    }

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

→ More replies (3)

3

u/p4bl0 1d ago

[LANGUAGE: OCaml]

Parsing was a breeze thanks to ocamllex. My only difficulty was understanding a bug in my implementation for part 2 that… wasn't there. I was running it on the sample rather than on my actual input 😅.

Part 1

Part 2

→ More replies (2)

3

u/UseUnlucky3830 1d ago

[LANGUAGE: Julia]

I maintain a set of all possible numbers that can be reached. Initially, the set has only one element, {0}. Each button press adds all the numbers that can be reached by pressing any of the buttons. For part 2, after adding the numbers, I remove those with more than 4 digits and check until the set no longer changes.

GitHub

3

u/chickenthechicken 1d ago

[LANGUAGE: C]

A bit tedious handling all of the different button cases. My Part 1 solution had a glaring mistake with [A->B] (fixed now) that somehow wasn't an issue for both the example and input case. This screwed me over for Part 2 as it gave me too much confidence that I was handling the buttons correctly.

Part 1

Part 2

3

u/xoronth 1d ago

[LANGUAGE: Eiffel]

paste

Day 5 means it's E day (would have been funny if the fifthglyph challenge was today), so today's new language is Eiffel! This is a port of my Python solution for the most part. The language definitely spooked me a bit at first but after using it for a bit it's not too bad.

3

u/DeadlyRedCube 1d ago edited 1d ago

[LANGUAGE: C++23]

GitHub: original implementation (parts 1 & 2)

GitHub: optimized implementation

Part 1 finished at 18:23, Part 2 at 33:45

For Part 1, I did the simplest possible implementation, just three loops stacked on top of each other wearing a trench coat:

for each button:
  v0 = Push(button, 0) // push the button starting with a value of 0
  for each button:
    v1 = Push(button, v0)
    for each button:
      valueSet.add(Push(button, v1))

For Part 2, I also started with a relatively straightforward implementation, testing every button on every element in the set, adding new values into the set until the set size doesn't change after an iteration:

valueSet.add(0)
while true
  newValueSet = {}
  for each value in valueSet:
    for each button:
      // Push this button from this value and add the result to the "new" set
      newValueSet.add(Push(button, value))
  valueSet = union(valueSet, newValueSet)
  if valueSet size didn't change:
    break // No new values were found, so we're done!

That initial implementation wasn't that fast, though - total runtime was 112.50 on my i7700.

To optimize:

  • I changed how the button parsing worked, making a little Button struct (rather than separating into strings and parsing them every time we push a button)
  • Changed the "octal" and "digit replace" buttons to not use strings (just manipulating the digits directly in the int)

Part 1 didn't change, I don't think it would have gotten much faster to not just do the three loops.

For Part 2, rather than testing every button in the value set over and over (wasteful!) it does something more akin to pathfinding:

// start with the values we got from part 1,
//  rather than starting from scratch
untriedStack.pushMultiple(valueSet)

while untriedStack is not empty:
  v = untriedStack.pop()
  for each button:
    newV = Push(button, v)
    valueSet.insert(newV)
    if newV was not already in valueSet:
      untriedStack.push(newV)

EDIT: Realized that I could optimize further by just using an array of 10,000 booleans that get set to true, rather than a set as described above, and add to the final sum only when setting a value in the array to true (rather than doing a separate "sum" pass), which shaved off 2/3rds of the runtime!

This now runs in 3.05ms 0.88ms, which is a number I like way better than 112 :D

3

u/amsterjoxter 1d ago

[LANGUAGE: JavaScript]

https://github.com/Joxter/advent-of-code/blob/master/2026/js/day05.js

The second version is a BFS that uses a plain array of size 9999 as the visited set. numbers[n] stores the step when n was first reached, so on each step I only expand the numbers found on the previous one. That way every number goes through the buttons exactly once, there's no hashmap or uniq, and the search stops by itself when a step finds nothing new. No magic round limit, and it runs in 4ms.

3

u/DelightfulCodeWeasel 1d ago

[LANGUAGE: C++]

Part 1 & 2

Naive solution: for all numbers in the current set, press all buttons. Repeat until no more numbers are added.

Doesn't fit on the Pico yet (~700kb heap used), probably won't have time to optimise the approach until later on in the month. I like the idea of treating this as a search problem, so I'll probably tackle the proper solution that way.

→ More replies (3)

3

u/NullQuantity325573 1d ago edited 1d ago

[Language: Pascal]

I way overengineered this one, but it was fun. It took me longer to define the data structures and write the parsing routine than it did to actually implement the solution. I might go back and explore FPC's regex facilities later today and see if I can make the parsing much more pleasing to read...it's kind of ugly right now, but it's functional, and more importantly, it works. Edit: I reworked parsing to use RegExpr, no major change in performance seen.

Part 1 is pretty simple - just iterate over all combinations of 1, 2, or 3 buttons, keep the resulting values in a set to avoid duplicates, and then sum up all the values in the set to get the answer.

For Part 2, essentially BFS, recognizing that all the numbers must be between 0-9999, or else they would have more than four digits.

Both parts run in less than a second on my x86_64. On the 68000-based Amiga, part 1 runs in 22 seconds. Part 2 runs in about 12 minutes. Good things come to those who wait! 😄

https://github.com/apprenticewiz/AOC2026/tree/main/day05

3

u/JustinHuPrime 1d ago

[LANGUAGE: x86_64 assembly]

Part 1 took a while. I wanted to represent the state of the microwave as an array of digits, where an empty array means it's only got a zero. Based on that, I started writing lambda functions.

These would take in a closure argument and a wide pointer to a digits array (which they wouldn't consume), and return a (new) wide pointer, and I would represent them as a pair of a function pointer and a closure value. Function-pointer-and-closure is one way your compiler can implement lambdas, and it's also used in a lot of C callback functions. I did a low-level trick so I could put these into an array: I wrote them so that their calling conventions were identical and their representations were all the same size. You can do this in a high level language, but you usually need to create some sort of indirection to hold the lambdas that accounts for the potentially different closure types. Often, the type of a lambda is an unspeakable type because of the closure, so you couldn't even create an array of lambdas syntactically.

After a few more utility functions for converting a digit array to and from an integer, I parsed the input buttons into an array of lambdas.

Actually solving the problem would take a generative recursive graph traversal with a visited accumulator and a compound worklist containing a context accumulator. I checked if we'd seen the number before, and if we hadn't, I checked the traversal depth. If we were good to continue, I added the result of applying every single button to the worklist.

At this point, I spent a few minutes fixing bugs and edge cases in the lambdas - for example, did you know that nasm doesn't complain if you write div [rsp], but it instead assumes you're doing an eight-bit division? I then spent an hour trying to figure out why I was getting different results based on the order of the buttons before giving up and asking an LLM for a hint. My bug was that I was doing a depth-first traversal, so I could get to a number at the max number of button presses and mark it as visited despite a shorter number of presses possibly being able to reach it and thus needing to continue on, but being blocked by the earlier visit. I fixed this by appending nodes to visit onto the end of the worklist instead, turning this into a breadth first traversal.

Part 2 was basically part 1 (this is becoming a running theme this year), except I didn't track depth and I added a check at the top of the traversal loop to skip if the number was too long (because this would be a repeat of the previous number).

Part 1 runs in 1 millisecond, and part 2 runs in 0.25 seconds (my memory allocator is horribly slow). Part 1 is 11,872 bytes and part 2 is 11,840 bytes as executable files.

3

u/lboshuizen 1d ago edited 1d ago

[Language: F#]

github.com/lboshuizen/aoc26

One breadth-first search serves both parts: part 1 stops after three layers, part 2 wraps every button in the four-digit cap and runs until nothing new appears.

Some observations on my input:

  • Backspace turns the state space into one strongly connected component, since every value falls back to 0, yet removing it changes nothing: the same 8527 values stay reachable.
  • Every number below 1000 is reachable; the 1473 gaps all have four digits, and none ends in a digit you can append.
  • The deepest value takes 12 presses.

Code:

let octal = Seq.unfold (fun v -> if v = 0 then None else Some(v % 8, v / 8)) >> Seq.mapi (fun i d -> d * pown 10 i) >> Seq.sum

let button (b: string) =
    match b with
    | "oct" -> octal
    | "bksp" -> flip (/) 10
    | _ when b.StartsWith "*" -> (*) (int b[1..])
    | _ when b.StartsWith "/" -> flip (/) (int b[1..])
    | _ when b.Contains "->" -> let p = b.Split "->" in string >> String.replace [ p[0] ] p[1] >> int
    | _ -> function 0 -> int b | v -> int (string v + b)

let reachable depth buttons =
    let step (seen, frontier) =
        let next = (frontier |> Seq.collect (fun v -> buttons |> List.map ((|>) v)) |> Set.ofSeq) - seen
        seen + next, next
    iterate step (Set.singleton 0, Set.singleton 0)
    |> Seq.tail
    |> Seq.truncate depth
    |> Seq.takeWhile (snd >> Set.isEmpty >> not)
    |> Seq.last
    |> fst

let capped b v = let r = b v in if r > 9999 then v else r

let part1 = reachable 3 >> Seq.sum

let part2 = List.map capped >> reachable System.Int32.MaxValue >> Seq.sum
→ More replies (1)

3

u/wheresmylart 1d ago

[LANGUAGE: Python3]

Part1: Make each operation in the input a lambda function. Put them in a container and then use the Cartesian product to get every ordering of 3 of them. Apply them in turn, store the answer in a set, sum the results and you're done.

Part 2: Take all the results from part 1 and apply each operation to them. Store the results. Keep doing this on the new set until there are no new results. Done.

Paste

3

u/tcbrindle 1d ago edited 1d ago

[LANGUAGE: C++]

Quite a lot of code today, but nothing particularly clever: just loop around applying the button presses, stopping after three rounds (for part 1) or when we've added no new values (for part 2).

Unfortunately no constexpr today due to the use of a hash set to store unique values, much sadness.

Github: https://github.com/tcbrindle/advent_of_code_2026/blob/main/dec05/main.cpp

→ More replies (1)

3

u/giacomo_hb 1d ago

[LANGUAGE: F#]

Solution: basically a variation of a BFS.

3

u/xiety666 1d ago edited 11h ago

[LANGUAGE: C#]

public static int RunA(string[] lines)
    => Calc(lines, 3);

public static int RunB(string[] lines)
    => Calc(lines, 0);

static int Calc(string[] lines, int maxDepth)
{
    var buttons = Parse(lines);
    HashSet<int> results = [];
    Recurse(0, 0);
    return results.Sum();

    void Recurse(int screen, int depth)
    {
        if (screen <= 9999 && (depth < maxDepth || results.Add(screen) && maxDepth == 0))
            foreach (var button in buttons)
                Recurse(button.Apply(screen), depth + 1);
    }
}

https://github.com/xiety/AdventOfCode/blob/main/2026/0/Problem05/Problem05.cs

3

u/glebusharick 1d ago

[LANGUAGE: Lua]

Bruteforced part 1 with Cartesian product generator (was fun to write), BFS for part 2

Solution

3

u/pkusensei 1d ago

[LANGUAGE: Rust]

Not hard but tedious. Basically it's some parsing logic (in f(); I know, bad name) and different terminating conditions for recursion.

3

u/fnordargle 1d ago edited 1d ago

[Language: Perl]

my $inp = <>; chomp($inp); $inp =~ s/[\[\]]//g;
my @but = split( / +/, $inp);
my %poss = ( 0 => 3 );                      # Can get to 0 with 3 button presses reamining
my @todo = ( 0 );                   # TODO list of new/unprocessed numbers
my $p1=0; my $p2=0;
while( scalar( @todo ) > 0 ) {
    my $n = shift( @todo );         # Get next item to do
    $p1 += $n if( $poss{$n} >= 0 ); # Still within 3 button presses so add it to p1 score
    $p2 += $n;                      # We add this one to the p2 score
    foreach my $b ( @but ) {        # Loop through possible button presses on $n
            my $newn = $n;          # Default to original number
            if( $b =~ /^\d$/ ) {                    $newn = ($n*10)+$b;
            } elsif( $b =~ /^\*(\d)$/ ) {           $newn = $n*$1;
            } elsif( $b =~ /^\/(\d)$/ ) {           $newn = int($n/$1);
            } elsif( $b =~ /^(\d)->(\d)$/ ) {       my ( $f, $t ) = ( $1, $2 ); $newn =~ s/$f/$t/g;
            } elsif( $b eq "oct" ) {                $newn = sprintf("%o", $n);
            } elsif( $b eq "bksp" ) {               $newn = int($newn/10);
            } else { die "UNKNOWN: [$b]"; }         # Must have missed something
            next if( exists($poss{$newn} ) || length($newn) > 4 );  # Seen it before or it is too big
            # Otherwise we add it to list of new numbers to try
            $poss{$newn}=$poss{$n}-1;       # Set that we can get here with one fewer button presses left
            push( @todo, int($newn) );
    }
}
print "part1: $p1\npart2: $p2\n";

Pretty standard single pass BFS ensuring I don't try the same number twice. Records the number of button presses left at each number so I can do both parts at the same time.

Perl is great because you can abuse its loose types and just move between string and integer representations of numbers easily (the result of the oct button is a string but we don't care). Perl is sometimes a nightmare because relying on this can introduce really subtle and annoying to find bugs.

3

u/JWinslow23 1d ago

[LANGUAGE: Python]

Solution writeup

Code (GitHub)

I gotta say, I enjoyed this puzzle a lot. The process of finding the solution felt good for whatever reason...and my solution approach allowed me to get higher-order with it.

def create_button(label: str) -> Button:
    match label:
        case "oct":
            return lambda value: int(oct(value).removeprefix("0o"))
        case "bksp":
            return lambda value: value // 10
        ...

One thing I realized after staring at my solution long enough was that I could easily unify both parts into a single solution function, simply by saving the number of presses it takes to reach each value in the BFS; Part 1 is just the sum of those values that took 3 presses or less fewer, and Part 2 is the sum of all values.

→ More replies (2)

3

u/dkdkfiennwls 1d ago edited 1d ago

[Language: Python]

I used Python's structural pattern matching to parse the input, then just did the BFS frontier set thing.

def parse(s):
    match list(s[1:-1]):
        case ['o','c','t']:     return lambda v: int(f'{v:o}')
        case ['b','k','s','p']: return lambda v: v//10
        case ['*', a]:          return lambda v: int(a)*v
        case ['/', a]:          return lambda v: v//int(a)
        case [a, '-', '>', b]:  return lambda v: int(str(v).replace(a,b))
        case [a]:               return lambda v: 10*v+int(a)

keys = [ parse(s) for s in open('input.txt').read().split() ]

h = {0}
for _ in range(3):
    h = { f(v) for f in keys for v in h }
→ More replies (2)

3

u/IvanR3D 1d ago edited 23h ago

[Language: JavaScript] Part 1 & 2

My solutions: https://ivanr3d.com/blog/adventofcode2026.html

3

u/mschaap 1d ago edited 1d ago

[LANGUAGE: Raku]

class Button
{
    has Str $.label;

    has &!_apply = do given $!label {
        when / '[' (\d+) ']' / { my $a = ~$0; -> $n { ($n ~ $a).Int } }
        when / '[*' (\d+) ']' / { my $a = +$0; -> $n { $n * $a } }
        when / '[/' (\d+) ']' / { my $a = +$0; -> $n { $n div $a } }
        when / '[' (\d+) '->' (\d+) ']' / { my ($a, $b) = (~$0, ~$1); -> $n { $n.subst($a, $b, :g).Int } }
        when / '[oct]' / { -> $n { $n.base(8).Int } }
        when / '[bksp]' / { -> $n { $n.chop.Int } }
    }

    method apply(Int() $val)
    {
        my $new-val = &!_apply($val);
        return $new-val ≤ 9999 ?? $new-val !! $val;
    }
}

sub apply-buttons(@buttons, @nums)
{
    unique gather for @nums -> $n {
        take .apply($n) for @buttons;
    }
}

sub MAIN(IO() $inputfile where *.f = 'aoc05.input', Bool :v(:$verbose) = False)
{
    my @buttons = $inputfile.words.map: { Button.new(:label($_)) }
    my $seen = Set.new(0);
    my @frontier = 0;

    for 1..∞ -> $step {
        @frontier = apply-buttons(@buttons, @frontier).grep({ !$seen{$_} });
        $seen ∪= @frontier;
        say "# step $step: $seen.elems() numbers: ", $seen.keys.sort if $verbose;
        say "Part one: ", $seen.keys.sum if $step == 3;
        last unless @frontier;
    }
    say "Part two: ", $seen.keys.sum;
}

3

u/Jadarma 1d ago

[LANGUAGE: Kotlin]

Today's problem is all about parsing and creating lambdas. Not difficult at all, quite relaxing, in fact! I just modeled each button as an operation class, then wrote some minimal string manipulation (no regexes yet, for brevity) to extract the numbers from the input and construct the lambdas.

For part one, a simple triple-stacked for loop iterates through all combinations. For part two, we do the same, except using recursion, and having the stop condition that either we reached a number that would overflow the microwave's display, or we already reached that number (memoisation for pruning the search). Yay for brute force!

AocKt Y2026D05

3

u/Daniikk1012 1d ago

[LANGUAGE: Uiua]

Man I love Uiua's pattern matching!

As for the solution itself, brute-force for Part 1, ignoring the "at most" part and just doing exactly 3 button presses, since those happen to include presses to backspace when number is already 0, essentially a no-op.

For Part 2, unlike other Uiua solutions, I forgot that repeat has "converge" behavior (What too much BQN does to a man), so I decided to use a queue with a boolean array for keeping track which we've already visited. It's surprisingly not as ugly or slow as I thought, though it would have been much nicer with "converge".

Unfortunately, while I tried to avoid any bindings in solutions for previous days, here I had to name F, as I couldn't come up with a way to reuse its functionality by just shuffling arguments around. I could of course just duplicate it, but that's even worse than just admitting this small defeat.

↘¯1&fras"5.txt" "[9] [*9] [/2] [1->9] [oct] [bksp]"
∩(⊸≠@\s
  ⊜(°$"[_]"
    ⍣[0 0⋕ | 1 0⋕°$"*_" | 2 0⋕°$"/_"
    | 3∩⋕°$"_->_" | 4 0 0°"oct" | 5 0 0°"bksp"]))
F ← (
  ⊃⋅⊢⊙(°⊟↘1)
  ⨬(+×10⊙◌ | ×⊙◌ | ⌊˜÷⊙◌
  | ⌝⊥10⍜▽⋅∘⤚=⬚0↙↥1⊸⧻⊥10 | ⌝⊥10⊥8 | ⌊÷10)
)
⊃(∩(/+◴≡⬚0/F⧅⋅⋅1 3)
| ∩([0]↯1e4 0
    ⍢(⊂↘1⟜(⨬(⤚⋅≡(⨬⋅∘∘⊸<1e4⤚F)⤚⍜⊏⋅1|⋅[]⊙∘)◡⊏⊢)|>0⧻)
    /+⋅⊚)
)
⊓($Real₁|$Sample₁|$Real₂|$Sample₂)

3

u/cheese3660 1d ago

[LANGUAGE: Factor]

Link to the solution: https://github.com/cheese3660/aoc26-factor/blob/main/day-5/day-5.factor

I honestly really liked doing this puzzle in factor, it basically feels like the concatenative aspect of factor in it's own right, applying a sequence of operations to a value.

Factor also made the parsing and compilation of all the buttons into quotations dead simple - I could literally define them with the names given in the puzzle, like for an example

! Convert a number to a string, take the last character off, and convert it back to a number
: [bksp] ( n -- n ) number>string 1 head* string>number 0 or ;

For backspace

Or

! Convert in to a string, swap every occurence of A with B, then convert back to a number
: [A->B] ( in A B -- n ) [ number>string ] 2dip replace string>number ;

For the [A->B] button

Then when compiling a sequence for the 1-ary or 2-ary operators I could just do a curry or 2curry

Which for some more examples

: >[*A] ( seq -- quot/f ) [X]>X dup first CHAR: * = [ 1 tail-slice string>number [ [*A] ] curry ] [ drop f ] if ;

For the multiplication parser, which returns false or a quotation

Then I could just do a simple chain to parse all of them

: >[...] ( seq -- quot )
    dup >[/A]
    [ dup >[*A] ] unless*
    [ dup >[A->B] ] unless*
    [ dup >[bksp] ] unless*
    [ dup >[oct] ] unless*
    [ dup >[A] ] unless*
    nip
    ;

Anyways, for the first part, my algorithm to get the set was basically

Application(N, buttons, set) :=
    N = 0 -> set
    N > 0 -> set U Application(N-1, buttons, apply(buttons,set))

Where apply just makes a set from the application of each button to each member to a given set

Then for the second part, I basically kept track of what numbers were already visited and used a stack to queue up new numbers.

Honestly, a pretty fun challenge :3

3

u/SwampThingTom 1d ago

[LANGUAGE: Rust]

GitHub

In hindsight, I didn't need to use itertools for part 1. A simple BFS would have sufficed and that turned out to be what part 2 needed anyway.

→ More replies (1)

3

u/dkdkfiennwls 1d ago

[LANGUAGE: SQL]

Straightforward conversion of some Python I wrote but crazy that it works so well (in SQLite) paste

3

u/DuoSRX 1d ago

[LANGUAGE: Uiua]

B ← ⊜□¬⊸∊"[] \n"&fras"day5.txt"
F ← ⍣(
  ×⋕°(⊂@*)
| ⌊÷⋕°(⊂@/)
| ⌝⊥10⊥8°"oct"
| ⌊÷10°"bksp"
| ≡(⋕+×⊙⊸=⊙⊙°⋕)∩¤⊃-∘°$"_->_"
| +⊃⋕(×ⁿ⊙10⧻))
∩(/+⍥(◴⊂⟜(▽⊸<1e4♭≡◇˜F¤⊙B))⊙[0])3 ∞

For fun, 87 chars golfed version with the input manually parsed:

∩(/+⍥(◴⊂⟜(▽⊸<1e4♭⊂₆⊃(⌝⊥10⊥8|≡⍜°⋕(+×7⊸=@0)|≡⍜°⋕(+×8⊸=@1)|⊞×8_9|⌊⊞÷2_10|⊞+4_9×10)))⊙0)3 ∞

Uiua pad link

3

u/greycat70 1d ago

[LANGUAGE: Tcl]

Since the Bash version was so slow, I rewrote part 2 in Tcl. It runs in 111 ms (compared to several minutes for the Bash version).

I ran into something new here: a recursion limit! I didn't know Tcl had one. This problem exceeds the default limit, so I had to raise it.

→ More replies (1)

3

u/RendererOblige 1d ago

[LANGUAGE: SQLite]

Still following the same pattern in SQLite: parsing is horribly difficult, but SQL makes the actual solution easy: https://forge.axfive.net/AdventOfCode/2026/src/branch/main/day05.sql

86 lines to parse the input, and fewer than 20 for each actual solution.

3

u/ProbablyNotMI6 1d ago

[LANGUAGE: F#]

paste

Quite enjoyed today! Bounded recursion over a mutating set of novel states. Ca. 6ms/56ms. I'm really vibing with F# as a language, glad I chose it as this year's weapon of choice. Could likely make it a bit quicker if I dispensed with the string shenanigans.

3

u/boredompwndu 1d ago

[LANGUAGE: Microsoft Excel]

Code

Basically iterate this, last rounds outputs in, press all the buttons for each, keep anything we haven't seen before. Given in the paste the previous iteration was for YI, ive been pressing a lot of buttons. Something interferes with uniques doing pruning, so I had to make a second sheet for "did we see 1-9999." Ideally I just select the field of all outputs and excel gives me a sum on the bottom ribbon.

3

u/PhysPhD 1d ago

[LANGUAGE: Python]

Part two: paste

I initially worked it out with a networkx because I thought I needed nx.transitive_closure() following a comment from u/Boojum but then I didn't need it, so simplified to just a set and list.

Really pleased to have cracked this one in under 24 hours!

3

u/4th_Thunder 1d ago

[LANGUAGE: Python]

def create_button(label):
    match label:
        case l if l.isnumeric():
            return lambda current: 10 * current + int(l)
        case l if l.startswith('*'):
            return lambda current: current * int(l[1:])
        case l if l.startswith('/'):
            return lambda current: current // int(l[1:])
        case l if '->' in l:
            return lambda current: int(str(current).replace(*l.split('->')))
        case "oct":
            return lambda current: int(oct(current)[2:])
        case "bksp":
            return lambda current: current // 10

input = "[9] [*9] [/2] [1->9] [oct] [bksp]".split()
buttons = [*(create_button(label[1:-1]) for label in {*input})]

results, next = {0}, [{0}]

i = 0
while next[i]:
    next.append({button(current)
                for current in next[i]
                for button in buttons
                if button(current) <= 9999} - results)

    results |= next[i + 1]
    i += 1

print(sum(sum(presses) for presses in (next[1:4])))
print(sum(sum(presses) for presses in next))

u/4HbQ I am officially converted...

I kept trying to think "how would u/4HbQ write this..." and it came out quite similar haha. I can't figure out a nice way to format/stylize nested comprehensions especially if there's a condition added to them, but maybe I'm just not used to looking at them yet.

→ More replies (2)

3

u/Stano95 1d ago

[LANGUAGE: Haskell]

this was easier than yesterday's for me. All I really did was write a parser (which was maybe overkill tbh) and use a load of standard library functions to implement the various button presses

part 2 just needed a fairly simple breadth first search

write up is here https://stanosphere.github.io/aoc/2026/day-05/

3

u/rjray 1d ago

[LANGUAGE: Clojure]

GitHub

Pretty sure part 1 was over-engineered to the max. But I'm also pretty sure it would work with any input, as nothing in there is hard-coded (other than the limit of 3 button-presses).

Part 2 threw me off at first, until I realized the digit-limit would let me approach it with a breadth-first search approach.

3

u/reddit_Twit 1d ago

[LANGUAGE: Zig]

gist

Was hard for me, part 1 took 99.9% of time, and there was moment when all instruction checked, all test data right but real answer still wrong

3

u/Radiadorineitor 1d ago

[LANGUAGE: Dyalog APL]

p←' '∘≠⍛⊆⊃⊃⎕NGET'5.txt'1
F←{
    d←∊∘⎕D⍛⊆⍺
    '/'∊⍺:⌊⍵÷⍎⊃d
    '*'∊⍺:⍵×⍎⊃d
    '-'∊⍺:⍎(2⊃d)@(=∘⊃∘d)⍕⍵
    'b'∊⍺:⌊⍵÷10
    'o'∊⍺:10⊥8⊥⍣¯1⊢⍵
    10⊥⍵,⍎⊃d
}
G←{⊂∘⍋⍛⌷∪4∘≥⍤≢∘⍕¨⍛/,p∘.F ⍵}
+/G⍣3⊢0 ⍝ Part 1
+/G⍣≡0 ⍝ Part 2
→ More replies (1)

3

u/Ok-Cheetah-6817 1d ago edited 23h ago

[LANGUAGE: Python]

(edited to remove giant code blocks. I hard coded the buttons, what are you going to do about it :p?)

3

u/RookBe 23h ago

[LANGUAGE: Rust]

Rust that compiles to WASM that's used in a solver on my website

Bonus link at the top of the code to a blogpost about today explaining the problem, and my code.

3

u/MaTeIntS 23h ago

[LANGUAGE: ngn/k]

Had to solve on my phone on the way to work. Added actual parsing, a few newlines and comments back home.

i:" "\(*0:"5.txt")^"[]"    / buttons (w/o []) from input
prs:{p:"->"\x              / parse a button to an action
  $[2=#p    ;.p[1]/p[0]\$: /   A->B
    "*"=*x  ;(.1_x)*       /   *A
    "/"=*x  ;(-.1_x)!      /   /A
    "oct"~x ;10/8\         /   oct
    "bksp"~x;-10!          /   bksp
             .,[;x]@$:]}   /   A
a:(::),prs'i               / actions, including empty one
sf:{$[10000>t:x y;t;y]}    / the safety feature
+/? 0 {y@'x}/ !3#,a        / part 1
+/ ({x@<x}@?,/a sf'/:)/ 0  / part 2

3

u/CCC_037 23h ago

[LANGUAGE: Rockstar]

part 1

Well, this was.... interesting. Some fun things with string manipulation for some of the functions.

For some of them i prepended my string with a 0 to prevent it throwing an error converting an empty string to a number.

→ More replies (1)

3

u/sauntcartas 22h ago

[LANGUAGE: Raku]

Cool, my first serious effort using a Raku grammar.

grammar Microwave {
    token TOP { [ '[' <button> ']' ]+ % \s* }
    proto token button { * }
    token button:sym<digit> { \d+ }
    token button:sym<multiply> { '*' (\d+) }
    token button:sym<divide> { '/' (\d+) }
    token button:sym<convert> { (\d+) '->' (\d+) }
    token button:sym<oct> { oct }
    token button:sym<bksp> { bksp }
}

class Actions {
    method TOP($/) { make $<button>».made }
    method button:sym<digit>($/) { make -> $n { * × 10 + $n }(+$/) }
    method button:sym<multiply>($/) { make -> $n { * × $n }(+$0) }
    method button:sym<divide>($/) { make -> $n { * div $n }(+$0) }
    method button:sym<convert>($/) { make -> $n, $m { +*.subst($n, $m, :g) }(~$0, ~$1) }
    method button:sym<oct>($/) { make +*.base(8) }
    method button:sym<bksp>($/) { make * div 10 }
}

my @ops = Microwave.parse(get, actions => Actions).made;

sub reachable-numbers($limit) {
    sub recurse($seen, $to-try, $remaining-presses) {
        return $seen.keys unless $to-try & $remaining-presses > 0;
        my $new-nums = $to-try.keys.flatmap({ @ops».($^n) }).grep({ $^n < 10_000 && !$seen{$n} }).Set;
        recurse $seen ∪ $new-nums, $new-nums, $remaining-presses - 1;
    }
    recurse set(0), set(0), $limit;
}

say 'Part 1: ', sum reachable-numbers(3);
say 'Part 2: ', sum reachable-numbers(∞);

3

u/Probable_Foreigner 22h ago

[Language: C++]

https://github.com/AugsEU/AdventOfCode2026/blob/master/Day5.cpp

Decided to do it in C++ this year... pure pain lol. Standard library regex is so horrendous I decided to just go unga-bunga mode to parse the input.

For part 2 the only thing that really had to change was to use a local stack instead of a recursive loop because I ran into a stack overflow exception, but the algorithm is basically the same.

3

u/ExploitSage 21h ago

[LANGUAGE: Python]

Github

3

u/daic0r 21h ago edited 20h ago

[LANGUAGE: C++]

Solution

Part 1: no-frills DFS with recursion limit

Part 2: DFS with check for already encountered numbers

3

u/Kintelligence 20h ago

[LANGUAGE: rust]

GitHub

Part 1: swapping between a next and current list in a for loop 3 times, where we only put numbers in our next list if we have not seen the result before.

Part 2: similar, but just a queue which we only put numbers into if never seen before, and if smaller than 10000.

3

u/lucariomaster2 18h ago

[LANGUAGE: C++]

C++, no standard or external libraries. I used some object-oriented code and a linked list for this one!

Part 1

Part 2

→ More replies (2)

3

u/greenergarlic 15h ago

[Language: Crystal]

Code on GitHub

Approach: Originally tried a DFS over all permutations, but that was way too slow. Refactored into walking the button presses one at a time, building up a list of potential candidates as I went.

5

u/maneatingape 1d ago edited 1d ago

[LANGUAGE: Rust]

Solution 401µs 284µs 191µs 87µs.

BFS for both parts.

EDIT: Since we can process at most 10,000 numbers, switched to a faster branchless approach instead of a VecDeque.

EDIT 2: Got it down to 87µs by auto-vectorizing everything! The code is still surprisingly readable.

  • Unrolled the octal and replace functions to branchless code that can be auto-vectorized.
  • Pre-calculate all 9 buttons * 10000 values up front. This may seem inefficient but the compiler can auto-vectorize to use SIMD, so that this only takes a mere 24µs.
  • Re-write the BFS so that it only ever appends to a buffer. We process a button at a time over the frontier, allowing the compiler to auto-vectorize the inner loop.
→ More replies (4)

4

u/Smylers 1d ago edited 20h ago

[LANGUAGE: Vim keystrokes] Sorry, no time to explain, but:

:s/[][]//g|s/ /\r/g|%s/bksp/$r0hlx/|%s/^\d$/A&⟨Ctrl+V⟩⟨Esc⟩0lF0x⟨Enter⟩
:%s#[*/].#A&⟨Ctrl+V⟩⟨Esc⟩0@v#|%s#\v(.)-\>(.)#:s/\1/\2/g\⟨Ctrl+V⟩⟨Enter⟩⟨Enter⟩
:%s#oct#:s/.*/printf('%o',\&)\⟨Ctrl+V⟩⟨Enter⟩0@v⟨Enter⟩
Go111⟨Esc⟩yy888pVGg⟨Ctrl+A⟩:,$g/0/d⟨Enter⟩9ggqbqqaqqajO0⟨Esc⟩3@bJ@aqu
qbjx@-ggy$''k:norm@0⟨Enter⟩q2@bJ@a{9dd:sor u⟨Enter⟩:%s/^/+⟨Enter⟩vipJ0@v

That uses @vfrom the back of the fridge my Day 2 solution, which itself is a variation made up from previous years' ingredients. Define that first if you don't already have it, load today's input into Vim, type the above, and your Part 1 answer will appear. [Advent Games]

Update: Explanation now available, along with the solution reformatted to be (a bit) easier to read.

→ More replies (6)

2

u/hugh_tc 1d ago edited 1d 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:

iterate = lambda f, x: it.accumulate(it.repeat(f), lambda acc, f: f(acc), initial=x)
fix_pt  = lambda f, x: next(t for t, t0 in it.pairwise(iterate(f, x)) if t == t0)

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)?"

→ More replies (2)

2

u/Ok-Bus4754 1d ago edited 1d 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/captainAwesomePants 1d 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.

2

u/NullT3rminated 1d ago

[LANGUAGE: Clojure]

Longest parse function so far 😎

(defn day5-parse [s]
  (concat
   (map
    (fn [[_ n]] #(+ (* % 10) (parse-long n)))
    (re-seq #"\[(\d)\]" s))
   (map
    (fn [[_ n]] #(* % (parse-long n)))
    (re-seq #"\[\*(\d)\]" s))
   (map
    (fn [[_ n]] #(math/floor-div % (parse-long n)))
    (re-seq #"\[\/(\d)\]" s))
   (map
    (fn [[_ f t]] #(parse-long (str/replace (str %) (first f) (first t))))
    (re-seq #"\[(\d)->(\d)\]" s))
   (map
    (fn [_] #(parse-long (format "%o" %)))
    (re-seq #"\[oct\]" s))
   (map
    (fn [_] #(math/floor-div % 10))
    (re-seq #"\[bksp\]" s))))

(def day5-parsed (day5-parse (slurp "5.txt")))

(defn day5-solve-a [parsed]
  (apply
   +
   (set
    (for [f1 parsed
          f2 parsed
          f3 parsed]
      ((comp f1 f2 f3) 0)))))

(defn day5-solve-b [parsed]
  (let [safe-parsed (map (fn [f]
                           (fn [x]
                             (let [result (f x)]
                               (if (> result 9999) x result))))
                         parsed)]
    (loop [cur #{0}
           prev #{}]
      (if (= cur prev)
        (apply + cur)
        (recur
         (reduce #(into %1 (map %2 %1)) cur safe-parsed)
         cur)))))

2

u/No_Mobile_8915 1d 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

2

u/morgoth1145 1d ago edited 1d 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 match which 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 of google-re2 which 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!

2

u/xoronth 1d 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.

2

u/Mikey_Loboto 1d ago

[LANGUAGE: TypeScript]

GitHub

Hm, that was easier than last couple of days for some reason.

2

u/AKSrandom 1d ago edited 1d 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

def action(button: str):
    if button      == "[bksp]" : return lambda n : n // 10
    if button      == "[oct]"  : return lambda n :        int(oct(n)[2:])
    if button[1]   == '*'      : return lambda n : n *    int(button[2])
    if button[1]   == '/'      : return lambda n : n //   int(button[2])
    if len(button) == 3        : return lambda n : 10*n + int(button[1])
    a = button[1]
    b = button[4]
    return lambda n: int(str(n).replace(a, b))

def salesman_free_action(action):
    def wrapper(n):
        res = action(n)
        if res > 9999:
            return n
        else: 
            return res
    return wrapper

def parse_raw(raw: str):
    buttons = re.findall(r'\[.*?\]', raw)
    return [salesman_free_action(action(button)) for button in buttons]

2

u/agorism1337 1d ago edited 1d 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.

2

u/TreeSquirrles 1d 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.

2

u/BradleySigma 1d ago edited 1d ago

[LANGUAGE: Python]

z, p, q, f = {0}, {0}, set(), []
for r in map(lambda t: t.strip("[]"), open("input5.txt").read().split()):
    if r[0] == "*": f.append(lambda x, r=r: x * int(r[1:]))
    elif r[0] == "/": f.append(lambda x, r=r: x // int(r[1:]))
    elif "->" in r: f.append(lambda x, r=r: int(str(x).replace(*r.split("->"))))
    elif r == "oct": f.append(lambda x, r=r: int(oct(x)[2:]))
    elif r == "bksp": f.append(lambda x, r=r: x // 10)
    else: f.append(lambda x, r=r: 10 * x + int(r))
for k in range(3): z |= {i(j) for i in f for j in z}
while p: q |= (p:={i(j) for i in f for j in p if i(j) <= 9999 and i(j) not in q})
print(sum(z), sum(q))

2

u/yieldtoben 1d ago edited 1d 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

2

u/Crusaderkingo2027 1d ago

[LANGUAGE: Python]

This reminded me of the recursion and dynamic programming lab assignments I used to do in college.

Part 1:

lines = [line.strip() for line in open('input.txt')]
instructions = [i[1:-1] for i in lines[0].split()]

def apply_instruction(num: int, instruction: str) -> int:
    if len(instruction) == 1:
        return int(str(num) + instruction)
    if instruction[0] == '*':
        return num * int(instruction[1:])
    if instruction[0] == '/':
        return num // int(instruction[1:])
    if '->' in instruction:
        split = instruction.split('->')
        old = split[0]
        new = split[1]
        return int(str(num).replace(old, new))
    if instruction == 'oct':
        return int(f'{num:o}')
    if instruction == 'bksp':
        if num < 10:
            return 0
        return int(str(num)[:-1])

def get_nums(num: int, nums: set, instructions_left: int, instructions: list[str]) -> set:
    nums.add(num)
    if instructions_left > 0:
        for instruction in instructions:
            new_num = apply_instruction(num, instruction)
            get_nums(new_num, nums, instructions_left - 1, instructions)

nums = set()
get_nums(0, nums, 3, instructions)
print(sum(nums))

Part 2:

lines = [line.strip() for line in open('input.txt')]
instructions = [i[1:-1] for i in lines[0].split()]
visited = set()

def apply_instruction(num: int, instruction: str) -> int:
    original_num = num 
    new_num = None

    if len(instruction) == 1:
        new_num = int(str(num) + instruction)
    elif instruction[0] == '*':
        new_num = num * int(instruction[1:])
    elif instruction[0] == '/':
        new_num = num // int(instruction[1:])
    elif '->' in instruction:
        split = instruction.split('->')
        old = split[0]
        new = split[1]
        new_num = int(str(num).replace(old, new))
    elif instruction == 'oct':
        new_num = int(f'{num:o}')
    elif instruction == 'bksp':
        if num < 10:
            new_num = 0
        else:
            new_num = int(str(num)[:-1])

    return new_num if len(str(new_num)) < 5 else original_num

def get_nums(num: int, nums: set, visited: set, instructions: list[str]) -> set:
    if num in visited:
        return
    visited.add(num)
    nums.add(num)
    for instruction in instructions:
        new_num = apply_instruction(num, instruction)
        get_nums(new_num, nums, visited, instructions)

nums = set()
get_nums(0, nums, visited, instructions)
print(sum(nums))

2

u/TiCoinCoin 1d ago edited 1d 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). Edit: down to 1.5sec with python!

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".

2

u/honey-pony 1d 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.

fun make_button(what: int, num1: int, num2: int) -> fun(int) -> int {
    if what == 'N' {
        |x| x * 10 + num1
    }
    else if what == '*' {
        |x| x * num1
    }
    else if what == '/' {
        |x| x / num1
    }
    else if what == '>' {
        |x| replace(x, num1, num2)
    }
    else if what == 'o' {
        decimal_coded_octal
    }
    else { // what == 'b'
        |x| x / 10
    }
}

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.

2

u/Wayoshi 1d 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).

2

u/Andreasnl 1d ago edited 1d ago

[LANGUAGE: Uiua]

B ← ⨬(
  ∘
| +9×10
| ×9
| ⌊÷2
| ⍜°⋕(+×8⊸=@1)
| °⊥₁₀⊥₈
| ⌊÷10
)
F ← ⨬◌⊙◌ ≤4⧻⊸⊥₁₀⊸B # Four digits max
N ← ⍆◴♭⊞F⇡7        # All possible next values
/+◴≡∧F ⧅⋅⋅1 3 ⇡7 0 # Part 1
/+⍥N∞ 0            # Part 2

2

u/TheZigerionScammer 1d ago edited 1d 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

int("123", 8)

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

→ More replies (2)

2

u/Boojum 1d ago edited 1d 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.

import itertools

b = { ( lambda v, i = int( w[ 1 : ] ): v * i )    if '*' in w else
      ( lambda v, i = int( w[ 1 : ] ): v // i )   if '/' in w else
      ( lambda v, i = p[ 0 ], j = p[ 1 ]: int( str( v ).replace( i, j ) ) )
                                                  if len( p := w.split( "->" ) ) == 2 else
      ( lambda v: int( oct( v )[ 2 : ] ) )        if w == "oct" else
      ( lambda v: v // 10 )                       if w == "bksp" else
      ( lambda v, i = int( w ): v * 10 + i )      # [d]
      for w in open(0).read().replace( '[', '' ).replace( ']', '' ).split() }

print( sum( { k( j( i( 0 ) ) )
              for i, j, k in itertools.product( b, repeat = 3 ) } ) )

v, q = set(), [ 0 ]
while q:
    p = q.pop()
    for i in b:
        n = i( p )
        if n <= 9999 and n not in v:
            v.add( n )
            q.append( n )
print( sum( v ) )

2

u/PendragonDaGreat 1d 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.

2

u/KyleGBC 1d ago

[LANGUAGE: Rust]

Solution

Back to back easy days, I hope tomorrow is a hard one :P

2

u/Conceptizual 1d 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.

2

u/Diamons 1d 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.

2

u/aashutoshr 1d 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.

2

u/Old-Dinner4434 1d ago

[LANGUAGE: TypeScript]

GitLab

Part 1 completed in 6.12ms, and part 2 completed in 18.89ms.

2

u/ShraddhaAg 1d 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.

2

u/ZeroTerabytes 1d ago edited 1d 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.

2

u/Fuzzy_Patterns 1d ago

[LANGUAGE: Nim]

Part1: bruteforce
Part2: recursive DFS with hashset, so we don't repeat states.

Solution on Codeberg: solution.nim

2

u/sim642 1d 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.

2

u/FruitdealerF 1d 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

2

u/light_ln2 1d ago edited 1d ago

[LANGUAGE: Python]

ops = [op[1:-1] for op in open('in05').read().split()]
o,r=lambda x:int(oct(x)[2:]),lambda x,i,j:int(str(x).replace(str(i),str(j)))
do=lambda p,x: ('o(x)' if 'o' in p else f'r(x,{p[0]},{p[3]})' if '-' in p else
  'x/10' if 'b' in p else 'x*10+'+p if len(p)==1 else 'x'+p).replace('x',x)
f = lambda N: N.union(*[{int(eval(do(p,str(x)))) for p in ops} for x in N])
f2 = lambda r,N={0}: N if r==0 else f2(r-1,f(N)-{*range(10**4,10**5)})
print('day05', sum(f2(3)), sum(f2(15)))

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!

2

u/winkers787 1d ago

[LANGUAGE: ZIg]

I had a lot of fun with this one, not sure if everyone will solve it with recursion, but for me the problem really fell into place after that thought. (not sure how else you could but I'm interested to see other solutions) I don't really have much experience with using it, much less in a lower level language where you have to pass around pointers and such.

I think I went a bit heavy with the abstractions with this one, I might clean it up eventually but for now i must sleep (it is 1 a.m. here I stayed up too late for this one)

Part 2 Solution - 1.64 ms

→ More replies (1)

2

u/Daniel_Rybe 1d ago edited 1d ago

[LANGUAGE: Odin]
https://github.com/DanRyba253/aoc26/blob/main/day5/main.odin
First day that I feel like splitting the solution into multiple files.

I'm glad Odin has array programming features like being able to 'and' two bool arrays element wise. It saved me some time in part 2.
Though, I initially wanted to use bit_set[10000; [16]u64] which would have been even cleaner and faster, but there's a bug with the Odin compiler right now that makes it impossible to use. Oh well.

Edit: Looking at other solutions, I haven't even considered a bfs for part 2. May try to see if it's faster later.

Edit2: Yeeeah, so after refactoring my solution as a bfs, both parts are 6 to 7 times faster.
Part1: 73μs -> 13μs
Part2: 6.8ms -> 1.2ms

2

u/Alpha_wolf_80 1d ago

[Language: Python]

This one ended up being a lot simpler than I initially thought. The first one can be solved in O(n^3) and the second one can be solved using a non-recursive BFS/DFS implementation. There is not a lot to say or optimize for this particular problem because you will have to generate all the possible combinations for addition. Moreover, certain operations end up being non-linear, which doesn't help in math. So, essentially the solution presented below is as optimal as you can get.

Part 1: 0.28ms

Part 2: 15.4ms

Code for both part 1 and 2: Advent-Calendar-Python/2026/5.py

2

u/anaseto 1d ago

[LANGUAGE: Goal]

Still fits in 80x5 today, but quite tightly for parsing: here's the same solution with shorter lines and extra comments. I parse the buttons into pervasive (vectorized and quite fast) functions, and then, iterate by applying all buttons to all reached numbers, three times or until convergence (keeping values under 10000).

p:{?[1~&x;{(~y)'["i"$($'y)+$'x;x]}["i"$x]; "*"¿x;("i"$1_x)*; "/"¿x;(-"i"$1_x)!
    "->"¿x;{"i"$sub[x;y]@$'z}."->"\x; "oct"~x;{"i"$"%o"$x}; {0 nan"i"$-1_$'x}]}
b:p'"[ ]"!-read"i/05" / parsed buttons
say+/3{?x,,/b@`x}/,0 / part1
say+/{?x,(10000>)#,/b@`x}/,0 / part2

2

u/cicadanator 1d ago

[LANGUAGE: Javascript - Node JS]

I used depth first search to and math to avoid costly string parsing and find a solution to part 1. Part 2 required only minor alterations to this search and button press calculations to give the correct result.

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

2

u/WesternNicator 1d ago

[LANGUAGE: Anathame]
Advent of langjam continues. Today I added fanout/juxtapose as a circumfix operator.

app =\λ mul,10 add,𝕪
bksp =\ div,10 floor
oct =\ base,8 antibase,10
replac =\λ ApplyUnder replace,𝕪 base,10
buttons = ⟦app,6 bksp mul,8 app,9 replac,[1_9] 𝓌{Switch const,4 replac,[0_4]} (div,3 floor) mul,9 oct⟧ # input
part2 =\ buttons |𝓈 Replaceif greater,9999
\ Repeat,∞ (Flatmap part2 deduplicate) sort sum

2

u/maitre_lld 1d ago

[Language: Python]
https://github.com/MeisterLLD/aoc2026/blob/main/5.py

Just a standard BFS with distance dictionnary. Didn't want to implement a queue / BFS in Haskell.

2

u/mstksg 1d ago

[LANGUAGE: Haskell]

https://github.com/mstksg/advent-of-code/blob/main/reflections/2026/day05.md

Advent of Parsing Instructions today heh. But overall not too bad.

parseButt :: String -> Int -> Int
parseButt = \case
  ['*', n] -> (* digitToInt n)
  ['/', n] -> (`div` digitToInt n)
  [c, '-', '>', d] -> read . map (\r -> if r == c then d else r) . show
  "oct" -> read . flip (showIntAtBase 8 intToDigit) ""
  "bksp" -> (`div` 10)
  c -> (+ read c) . (* 10)

parseButts :: String -> [Int -> Int]
parseButts = map (parseButt . tail . init) . words

The typical "try N combinations of all things" is replicateM for lists:

part1 :: String -> Int
part1 = sum . nubOrd . map (foldr ($) 0) . replicateM 3 . parseButts

For part 2 I pulled out my pre-written flood fill algorithm: we are basically "flood filling" all of the numbers reachable from 0 with buttons.

floodFill :: Ord a => a -> (a -> [a]) -> Set a
floodFill x0 f = go S.empty (S.singleton x0)
  where
    go innr outr
      | S.null outr' = innr'
      | otherwise = go innr' outr'
      where
        innr' = S.union innr outr
        outr' = foldMap (S.fromList . f) outr `S.difference` innr'

This works nicely with sequence :: [Int -> Int] -> Int -> [Int], so sequence . parseButts is literally the expander function (once we add the 9999 cutoff) for our flood fill.

part2 :: String -> Int
part2 = sum . floodFill 0 . rmap (filter (<= 9999)) . sequence . parseButts

2

u/AllanTaylor314 1d ago edited 1d ago

[LANGUAGE: Python] 00:14:07/00:19:26

Initial spaghetti & improved sauce

I didn't (initially) write a parser for this. My real input lambdas were pretty similar to the test_buttons in the spaghetti. I wrote a parser later.

Forgot what combinations were so my answer was too low. Switched to nested loops (it is leftover spaghetti, afterall).

For part 2, I technically have an iterative breadth-first search. I loop until it stops finding more numbers (which we'll see repeated in the Uiua later). I lost a minute by submitting the example solution - doh. I didn't need to sort the set - just needed to be a fresh copy.

[LANGUAGE: Uiua]

pad thai and sauce

Today's bug that the example doesn't catch: Uiua's ⊥₁₀0 (base,10 0) returns [] so [0->1] did not work. As such, I switched to string manipulation, because at least 0 is "0".

The stack manipulation (bring 3rd to top) with ⊃⋅⋅∘⊙∘ is a lil cursed. Is ⤙⊙⊙◌ any better?

Anyway, Uiua doesn't really have first class functions I can chuck at the stack nor eval, so I parse the button each time I use it. I switch by length and specific chars.

I use rep() inf to do fixed point iteration. I forgot that it only checked the top of the stack, so I had to rearrange the arg order so the array of reachable numbers was on top (this one is nicer imo - less dipping). I originally had the buttons on top. I briefly used flip (deprecated) four times to have the right order when checked.

Replace isn't easily pervasive, so I had to use row,0

[Advent Games]

Oh, and have the leftovers in a tupperware container (half punch card)

$ [9] [*9] [/2] [1->9] [oct] [bksp]
3 ∞ 0 ⊜□⊸>@ ⍣(&fras"05.txt"◌|∘)
⊓$Part₁$Part₂∩⊓/+◌∩⌟₂⍥(▽⊸<1e4⍆◴⊂♭◡≡⌞◇˜(
⌊⨬(+⋕⊓⊡₁×₁₀|⨬×÷⊓=⋕@/⊢₂↘₁|⋕°⋕₈◌|⨬⋅÷₁₀(
≡₀(⋕⍜▽◌⤚=°⋕⤙⊙⊙◌)∩⊢°$"[_>_")=@-⊸⊡₂)-₃⊸⧻))

2

u/vubik 1d ago

[LANGUAGE: Rust]

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

For both parts use DFS, but with different criteria for pruning: in part 1 we have the restricted depth and in part 2 we can only recurse on numbers we have not yet seen. As usual, parsing assumes the input is correctly formed, without extensive validation.

One optimization I did is pre-computation for [oct] button transformation for numbers less than 10000.

2

u/oupsman 1d ago

[LANGUAGE: Golang]

It's fun to dust off algorithms I don't really use every day, that's why I enjoy AOC so much.

Today, BFS for the win

Both parts run in 8ms on my laptop

https://raw.githubusercontent.com/Oupsman/AOC2026/refs/heads/master/D05/day05.go

2

u/runnerx4 1d ago edited 1d ago

[LANGUAGE: Guile Scheme]

It's BFS but I figured out to fit BFS into a SRFI-42 comprehension with the :while and the infinite :integers generators

(define (all-possible-numbers buttons part1?)
  (let ([visited (make-hash-table)]
        [display-q (make-q)])
    (enq! display-q "0")
    (hash-set! visited "0" #t)
    (sum-ec (:while (:integers presses)
                    (if part1?
                        (< presses 3)
                        (not (q-empty? display-q))))
            (:range i (q-length display-q))
            (:let disp (deq! display-q))
            (:list button buttons)
            (:let next (button-press button disp))
            (not (> (string-length next) 4))
            (not (hash-ref visited next))
            (begin
              (hash-set! visited next #t)
              (enq! display-q next)
              (string->number next)))))

full code paste

2

u/atreju3647 1d ago

[Language: python]

This solution generates a custom search using the input. It runs 1.5x faster than this solution, which uses a list of lambdas.

For reference, here is the generated code for the example input.

2

u/maarteq 1d ago

[Language: python]

solution

a wrote a function to press simulate a button press.

for part 1 i use 3 for loops

for part 2 i explored the space with recursion, I had to increase the recursion limit in python.

2

u/smallpotatoes2019 1d ago

[LANGUAGE: C#]

Solution for both parts.

Just running all the possible button presses here. Then in Part 2, making my array to store them bigger and just not logging any results that don't fit in. I assumed (and perhaps got lucky) that when the total sum stayed the same after a round of button pushes, I would have the final total.

2

u/Aoyaba-Poett 1d ago

[LANGUAGE: Rust]

Topaz Paste Part 1 & 2

Using state machines.

2

u/musifter 1d ago

[LANGUAGE: Smalltalk (GNU)]

For this one I changed things up by doing BFS instead of DFS. I also got use the fact that BlockClosures in Smalltalk are closures. When I read the buttons in, I create code blocks and add them to the list... and the fact that they're closures means that the parsed digits (part of the local environment) get carried with the block for when it's run later.

Source: https://pastebin.com/y3cY33dY

2

u/HotTop7260 1d ago

[Language: Kotlin]

Here the full solution: Day 5

I might have "over-engineered" the operations part a bit, but it's a good example for the command pattern, if you are interested in this kind of stuff. I used two functions of my own Utility collection in the same repository. The link is for convenience (the import statement does not point to the file, because I used top-level functions).

The solution function for part 2 is a pure BFS without any extras attached to it. I think it is beautiful enough to show it:

private fun solve2(ops: List<Operation>): Long {
    val possibleOutcomes: MutableSet<Long> = HashSet()

    // BFS FTW
    val queue: Queue<Long> = ArrayDeque()
    queue.offer(0L)
    while (queue.isNotEmpty()) {
        val current = queue.poll()
        possibleOutcomes.add(current)
        for (op in ops) {
            val next = op.operate(current, maxFourDigits = true)
            if (next !in possibleOutcomes) {
                queue.offer(next)
            }
        }
    }

    return possibleOutcomes.sum()
}

Most of you will be familiar with BFS, but for those who are not, this example implementation might be of educational value (at least I hope so).

If you ask, why I picked "Long" instead of "Int": Sometimes AoC problems tend to require bigger integers than "Int" can provide. Often this will happen in part 2. Therefore I committed to "Long" in part 1. Here "Int" would have been enough, but I kept it.

BTW: I didn't feel like "regular expressions" today :-D

2

u/aknusmag 1d ago

[LANGUAGE: Rust]

Part 1: Implemented the instructions as described and iterated over results 3 times

Part 2: Implemented it as a BFS searching all possible values. If a value has been seen before, we can skip it because non of the instructions would produce any different value than last time.

Solution

2

u/Arctos_FI 1d ago

[LANGUAGE: C#]

I overcomplicated this way too much. But in the end got pretty fast solutions for each one (not anything over the top, it's the most obvious solution in a hind sight, but fast comapred to the one I started with that would've taken hours to compute). Hopefully I'll see the obvious solution at the beginning, instead hitting my head to the wall trying to get the inneficient solution coded.

Part 1

Part 2

2

u/fudeiq 1d ago edited 1d ago

2

u/PhysPhD 1d ago

[LANGUAGE: Python]

paste - just Part 1

I used itertools product and hardcoded functions (so it's just for my input).

Not sure how to tackle Part 2. Maybe I need to read up on BFS and deques first?

→ More replies (1)

2

u/aimada 1d ago

[LANGUAGE: Lobster]

Code

No set data structure so I used a boolean lookup array to replace linear array scans for O(1) lookups which made the execution time respectable.

2

u/Jdup1n 1d ago

[LANGUAGE: R]

Github link

For Part 1, I test all combinations of at most 3 keys and sum up the unique digits obtained.

For Part 2, a simple BFS is carried out by pressing all the keys for each number from 0 to 9999.

2

u/crumpis 1d ago edited 16h ago

[LANGUAGE: Python]

Link

Not much to say, it's just a straightforward implementation of the spec. Part 2 is just implementing the 4 digit cap and keeping a rolling set of any new numbers that showed up in the last step and rerun against that.

I did a half-baked optimization by storing both the string and integer representation of the current display number so I wouldn't have to eat the cost of conversion every step.

Ideally I'd be smarter in parsing the buttons as well so I don't need to keep converting what value is being multiplied or divided there too, but it's too early in the morning.

Note: since as given in the problem there's now a constant bound, Part 2 is actually O(1) whereas Part 1 is O( n3 ) :v

Edit: Refactored the whole thing as a BFS. Still a straightforward implementation of the spec, just with the one insight of how 3 button presses also grabs things of cost 0, 1 and 2.

2

u/SpaceHonk 1d ago

[Language: Swift]

code

Part 1 checks all 3-button combinations, part 2 is a straightforward BFS

2

u/r_so9 1d ago

[LANGUAGE: F#] paste

I went for readability instead of cleverness. Interesting bits: strongly typed operations, BFS.

type Button = 
    | Append of int64 | Multiply of int64 | Divide of int64 
    | Replace of string * string | Octal | Backspace

let press button current =
    match button with
    | Append x -> current * 10L + x
    | Multiply x -> current * x
    | // etc.

let pressAll value =  buttons |> Seq.map (fun button -> press button value)
let step values = values |> Seq.collect pressAll |> Set.ofSeq |> Set.union values
let part1 = Set.singleton 0L |> step |> step |> step |> Seq.sum

let part2 =
    let visited = HashSet<int64> [ 0L ]
    let queue = Queue<int64> [ 0L ]
    while queue.Count > 0 do
        let x = queue.Dequeue()
        for n in pressAll x do
            if n < 10000L && visited.Add n then
                queue.Enqueue n
    Seq.sum visited

2

u/SymmetryManagement 1d ago

[Language: Java]

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

memoized bfs to find all values, with precomputed values for most operations. O(NUM_OF_BUTTONS * MAX_DISPLAY_VALUE) i.e. O(NUM_OF_BUTTONS * 9999)

Part 1 68us
Part 2 570us

2

u/Nicolino14 1d ago

[LANGUAGE: Rust]

Link

It took me longer towrite the representation of the state than the rest.

Part1, just cycle through the instructions 3 times. On the first cycle only go through the [A] as the rest would produce 0s, I put all results into a set to prevent duplicates.

Part2

BFS.

Part1 runs in <1ms, Part 2 in 20ms

2

u/BlazingThunder30 1d ago

[Language: Kotlin]

https://git.bjornp.com/bjorn/adventofcode/src/commit/a1869f2a13fc10ef0d723fac1dccb421de25c816/java/solutions/y2026/src/test/kotlin/com/bjornp/aoc/solutions/y2026/Day5.kt

Implemented the operation parsing as a sealed interface where each button type is a concrete implementation. Somewhat over-engineered, but I always like taking the time to have a good foundation to actually solve the problem instead of figuring out I messed up the parsing after two hours.

Part 1 is pretty simple, runs buttons, buttons x buttons and buttons x buttons x buttons and sums up all the unique results. Part 2 uses a memoized BFS where we short circuit on numbers we've already seen. Probably could be more efficient by doing something with the 0-9999, but JUnit says this runs in ~30ms so I'm happy.

2

u/paulhaahr 1d ago

[Language: Quest]

The most fun part of this was parsing each button into a function from ints to ints – that just felt right in a functional language. Part 1 (explore) used a port of Python's itertools to Quest to try all n-press combinations of buttons; part 2 (exploreAll) did a straightforward breadth-first search. In both cases the search returns a SortedMap from the display values to the first button sequence to generate them, which was useful for debugging.

let applySeq(seq: Array(Button)) =
    begin
        let rec apply(seq: Array(Button) index: Int value: Int path: String):
                Tuple value: Int path: String end =
            if index < extent seq then
                let button = seq[index]
                apply(seq {index + 1} button.op(value) {path <> button.name})
            else
                tuple value path end
            end
        apply(seq 0 0 "")
    end

let explore(buttonPanel: String maxPresses: Int) =
    begin
        let buttons = vector.toArray(parseButtons(buttonPanel))
        let map = sortedMap.newIntMap(:String)
        for presses = 0 upto maxPresses do
            let it = itertools.productOf(array of(presses buttons))
            while iter.more(it) do
                let result = applySeq(iter.next(it))
                if not sortedMap.contains(map result.value) then
                    sortedMap.insert(map result.value result.path)
                end
            end
        end
        map
    end

let exploreAll(buttonPanel: String) =
    begin
        let buttons = vector.toArray(parseButtons(buttonPanel))
        let map = sortedMap.newIntMap(:String)

        let rec traverse(value: Int path: String): Ok =
            if {0 <= value} andif {value <= 9999} andif not sortedMap.contains(map value) then
                sortedMap.insert(map value path)
                for i = 0 upto {extent buttons} - 1 do
                    let button = buttons[i]
                    traverse(button.op(value) path <> button.name)
                end
            end

        traverse(0 "")
        map
    end

My Advent of Code repository: https://github.com/haahr/adventofcode
Quest repository: https://github.com/haahr/quest

2

u/CEOnism 1d ago edited 1d ago

[LANGUAGE: Javascript]

const input = "[9] [*9] [/2] [1->9] [oct] [bksp]";

const parse = raw => {
  let m;
  if (raw === 'oct') return { op: 'oct' };
  if (raw === 'bksp') return { op: 'bksp' };
  if ((m = raw.match(/^([*/])(\d+)$/))) return { op: m[1], n: BigInt(m[2]) };
  if ((m = raw.match(/^(\d+)\s*->\s*(\d+)$/))) return { op: '->', from: m[1], to: m[2] };
  if (/^\d+$/.test(raw)) return { op: 'append', digits: raw };
  throw new Error(
    `Unknown button.
    The authorities have been notified.`);
}

const tokenize = s => [...s.matchAll(/\[([^\]]+)\]/g)].map(([, raw]) => parse(raw));


const press = (v, b) => {
  const s = v.toString();
  switch (b.op) {
    case 'append': return BigInt(s + b.digits);
    case '*': return v * b.n;
    case '/': return v / b.n;
    case '->': return BigInt(s.replaceAll(b.from, b.to));
    case 'oct': return BigInt(v.toString(8));
    case 'bksp': return BigInt(s.slice(0, -1) || '0');
  }
};


// Breadth-First Search
const reachable = (buttons, { maxPresses = Infinity, limit = Infinity }) => {
  const tokens = tokenize(buttons);
  const seen = new Set([0n]);
  let frontier = [0n];
  for (let i = 0; i < maxPresses && frontier.length; i++) {
    const next = [];
    for (const v of frontier)
      for (const t of tokens) {
        const r = press(v, t);
        if (r > limit || seen.has(r)) continue;
        seen.add(r);
        next.push(r);
      }
    frontier = next;
  }
  return seen;
}



const sum = set => set.values().reduce((s, v) => s + v, 0n);
const p1 = sum(reachable(input, { maxPresses: 3 }));
const p2 = sum(reachable(input, { limit: 9999 }));


console.log(p1, p2);

2

u/Withered_Flower__ 1d ago edited 1d ago

2

u/mkinkela 1d ago

[LANGUAGE: C++]

I should probably use state with less info but it runs in 28.40 ms so I don't care that much.

Solution

2

u/jhandros 1d ago

[LANGUAGE: Python in Excel]
Part 1

z,p,q,f={0},{0},set(),[]
for r in map(lambda t:t.strip("[]"),xl("A1").split()):
 f.append((lambda x,r=r:x*int(r[1:])) if r[0]=="*" else (lambda x,r=r:x//int(r[1:])) if r[0]=="/" 
          else (lambda x,r=r:int(str(x).replace(*r.split("->")))) if "->" in r else (lambda x: int(oct(x)[2:]))
          if r=="oct" else (lambda x:x//10) if r=="bksp" else (lambda x,r=r:10*x+int(r)))
for k in range(3):z|={i(j) for i in f for j in z}
while p:q|=(p:={i(j) for i in f for j in p if i(j)<=9999 and i(j) not in q})
sum(z)

Part 2

sum(q)

2

u/jwezorek 1d ago edited 1d ago

[LANGUAGE: C++23]

I found this one easier than the two previous days in that there were no real gotchas.

For part 1 after parsing and implementing button logic etc. I wrote a function that returns the "k-permutations with repetition" and called that to just enumerate all ways of choosing three buttons, do all of those sets of three calls, and stored the values in a hash set. (In retrospect for correctness Id need the 1-permutations and 2-permutations too because the text says "at most three buttons" not "exactly three buttons" but on my input there were no unique values that could be created with 1 or 2 presses but not 3)

For part 2, reused the button evaluation code from part 1 but added a parameter to do the "but restrict to four digits" logic then just did a depth first search that does not traverse values it has already visited. Actually part 2 for me was easier than part 1 in that "k-permutations with repetition" is not something I can write off the top of my head whereas a DFS is.

[my code on github]

2

u/Lindi-CSO 1d ago

[LANGUAGE: C#]

Gotta admit, this morning my brain would not remember that recursion is even a thing.

I started with using my function to create all permutations up to size 3 for the first part and quickly realized, that that would not work for part 2.

After a breakfast and coffee, I finally remebered recursion with memoization is a thing, so I threw it together and voila it works for both parts. I really have to get my mind into puzzle mode for AoC, because that's not something I ever have to use in my day job -.-

Parts 1 & 2

2

u/Thick-Ad-9170 1d ago

[LANGUAGE: c++]

I first solve part1 and part 2 but cant' reach a solution that pass part2 with static_assert (compile time unit test).

Rules : constexpr capable, no for loop

AI: Deepseek 4.1 help me to solve the static_assert optimization

https://github.com/pcorbineau/aoc2026/blob/main/libs/day05/include/aoc2026/day05.hpp

2

u/Due_Scar_5134 1d ago

[LANGUAGE: JavaScript and Python]

https://github.com/onlyroz/advent-of-code-2026/tree/main/src/days/day05

I quite enjoyed this one. I ran a BFS starting from "0" and expanded each display value only once. Button presses cover digit append (replacing the display when it is "0"), multiply and divide, digit remapping, octal conversion, and backspace. For part 1 I stopped after three presses. For part 2 I allowed any number of presses but discarded results longer than four digits. The answer is the sum of all distinct displays interpreted as integers.

2

u/Zuomot 1d ago edited 1d ago

[LANGUAGE: Kotlin]

I wanted to get rid of all the stacks, dictionaries and any other dynamic data structures, also - no evil recursion or anything.

Here's all using only two BitArrays(10000) = 2.5KB of RAM (because it's sooo expensive nowadays). Part 2 only, without uninteresting parsing.

fun part2(data: String): Any {
    val buttons: List<Button> = parse(data)
    val found = BitArray(10000)
    val foundRecently = BitArray(found.size).also { it[0] = true }
    var result = 0
    var done = false
    while (!done) {
        var added = 0
        val foundNow = BitArray(found.size)
        repeat(found.size) { v ->
            if (foundRecently[v]) {
                buttons.map { it(v) }.forEach { n ->
                    if (n < found.size && !found[n]) {
                        found[n] = true
                        foundNow[n] = true
                        added += n
                    }
                }
            }
        }
        foundNow.copyInto(foundRecently)
        result += added.also { if (it == 0) done = true }
    }
    return result
}
→ More replies (3)

2

u/jad2192 1d ago

[LANGUAGE: Python]

https://github.com/jad2192/advent_of_code_2026/blob/master/aoc2026/day05.py

Probably a bit overengineered with OOP but the idea is you really only need to track the set of possible end values, no need for dynamic or DFS/BFS, then apply then add where you end up after each possible button press on that input. Both parts and my tests run in under a quarter of a second.

→ More replies (2)

2

u/olamberti 1d ago

[LANGUAGE: Python]

Both parts are solved in a single BFS, using two sets: front for newly discovered numbers and seen for all previously discovered numbers.

Part 1: Sum all reachable numbers after the third BFS iteration, corresponding to a maximum of three button presses.

Part 2: Continue the traversal until no new numbers can be discovered.

buttons = [b[1:-1] for b in open("d05.txt").read().split()]

def press(n, b):
    if b.isdigit(): return 10*n + int(b)
    if b[0] == "*": return n * int(b[1:])
    if b[0] == "/": return n // int(b[1:])
    if "->" in b:   return int(str(n).replace(*b.split("->")))
    if b == "oct":  return int(oct(n)[2:])
    if b == "bksp": return n // 10

seen, front, p = {0}, {0}, 0
while front or p < 3:
    front = {m for n in front for b in buttons
             if (m := press(n, b)) <= 9999} - seen
    seen |= front
    p += 1
    if p == 3: print(sum(seen))
print(sum(seen))
→ More replies (2)

2

u/tranjeroex 1d ago

[LANGUAGE: Roc]

Part2: Start with "seen" numbers ([0]) and "new added numbers" ([0]). Apply all buttons to the new added numbers and keep only the ones that haven't been seen yet and are < 10_000. Compute union of seen + new added numbers and iterate again. Stop when there are no new numbers.

Github

2

u/fridi_s 1d ago

[LANGUAGE: Fuzion]

GitHub

Main difficulty was the choice of a functional data structure to collect the results. Fuzion provides an efficient partially sorted set called ps_set for this.

2

u/TheScown 1d ago

[LANGUAGE: Scala]

Link

BFS and prune states which have too many buttons presses or which make the string representation of the number too long.

2

u/leftfish123 1d ago

[LANGUAGE: Python]

I now see that BFS was probably a better option, but my first thoughts went towards DFS, so I dusted it off. After 7 years of AoCing I'm still not happy doing anything recursive, so I just went with the iterative implementation. As it turned out when I tried the recursive one for part 2 later, after getting the starts, it easily exceeded the default recursion depth.

2

u/Sad_Listen_4414 1d ago

[LANGUAGE: Lean]

Part 1 & 2: spec, manual solution, ai solution, ai solution's proof

$ aoc check 5
2026 day 5           ok
    ✓ part1_correct
    ✓ part2_correct

$ aoc bench 5
Part 1:
  min 1.0 µs · median 1.3 µs · mean 1.4 µs · p99 1.8 µs  (1000000 runs)
Part 2:
  min 104.6 µs · median 117.1 µs · mean 119.3 µs · p99 152.0 µs  (16752 runs)

2

u/wjholden 1d ago

[LANGUAGE: Rust]

Table-driven testing for the win!

#[test]
fn buttons() {
    for (mut screen, button, output) in [
        (Microwave(0), Button::Literal(3), Microwave(3)),
        (Microwave(123), Button::Multiply(11), Microwave(1353)),
        (Microwave(118), Button::Divide(7), Microwave(16)),
        (Microwave(16), Button::Divide(7), Microwave(2)),
        (Microwave(101), Button::Replace(1, 8), Microwave(808)),
        (Microwave(0), Button::Replace(0, 8), Microwave(8)),
        (Microwave(123), Button::Oct, Microwave(173)),
        (Microwave(173), Button::Oct, Microwave(255)),
        (Microwave(26), Button::Bksp, Microwave(2)),
        (Microwave(2), Button::Bksp, Microwave(0)),
    ] {
        screen.press(&button);
        assert_eq!(screen, output);
    }
}

Code.

2

u/andrewsredditstuff 1d ago

[LANGUAGE: C#]

It was a little faster before squishing all the for loops into a single line of LINQ, but it's a reasonable balance between speed and unreadability (and I like it when the code fits onto a single page).

Got a 2x speed-up when I realised I didn't have to operate on the full set of results on every round of presses, just the ones that were added in the last round.

github

2

u/nilgoun 1d ago

[LANGUAGE: Rust]

First time posting this year, but I think this was fun :) Trimming down the tracing state (started way too complex...) was kinda nice.

Solution on paste

2

u/azzal07 1d ago

[LANGUAGE: awk]

function O(c,t){return!c?t:O(int(c/8),c%8t)}Q=b="b"{for(;i=split(Q,q);
y++)for(Q=z;a<NF||n=q[i--](a=z);)if(!u[x=D($++a,+n)]++&&x<1e4){Q=Q" "x
y<3&&A+=x;B+=x}}function D(e,c){return+int(b~e?c*.1:3<gsub(/[^0-9]/,z,
e)?e?gsub(D(b,e),e%10,c)^0*c:O(c):"*"~$a?c*e:"/"~$a?c/e:c e)}$0=A"\n"B

Was surprised to see simple recursive dfs search was plenty fast enough for part 2, but had to rewrite since goawk hit recursion limit at 1000. The bfs version also solves part 1 nicely at the same time.

2

u/hextree 1d ago

[LANGUAGE: Python]

Code

Video

Essentially brute force for part 1 followed by depth first search for part 2.

2

u/e_blake 1d ago edited 1d ago

[LANGUAGE: m4] [Advent Games]

m4 came out 49 years ago, in 1977. I think that qualifies as vintage ;) And the name - doesn't "mmmm" imply tastiness?

m4 -Dfile=path/to/input day05.m4

(I'll probably further tweak my code to use a deprecated cookie, somehow...)

Half the battle was figuring out how to parse things in a way that was easy to reuse; I ended up turning buttons into a macro listing consecutive actions forming all branch-points from a given state, with

define(`_parse', ``apply($1, $$2)'parse(1, ')
define(`parse', `ifelse(`$2', `', `', `$2', `oct', `_$0(`eval($$1,8)', 2)',
  `$2', `bksp', `_$0(`eval($$1/10)', 2)', len($3), 1,
  `_$0(`translit($$*)', 2)', index(`*/', substr(`$2', 0, 1)),
  -1, `_$0(`ifelse($$1, 0, $2, `$$1'$2)', 2)', `_$0(`eval($$1$2)', 2)')')
define(`use', parse(1, translit(include(defn(`file')), nl`>][' -, `),)')))

Thus, the example input produces a single macro use:

m4trace: -1- define(`use', `apply(ifelse($1, 0, 9, `$1'9), $2)apply(eval($1*9), $2)apply(eval($1/2), $2)apply(translit($1,1,9), $2)apply(eval($1,8), $2)apply(eval($1/10), $2)')

I initially wrote part 1 with a depth-first search. My first cut solved the example but came in too low for my input, because I was pruning values the first time they were seen, but whereas the example had [bksp] last, and managed to visit all unique values before pruning, my input had [bksp] near the front and happily pruned out values I needed, so my first submission was too low. (And did anyone else notice that [bksp] would be the same as [/10]?)

Once I switched to a breadth-first search, the right answer for part 2 popped out a lot faster, in under 150ms runtime, and with max depth 13 for my input (16 for the example), because pruning at either depth 3 or 4 digits (for running part 1 and 2 in parallel) was a LOT easier than trying to figure out if I'm pruning prematurely or duplicating search efforts on a DFS.

I'm also impressed that we're at 5/12 days and I still haven't had to whip out 64-bit math.

→ More replies (2)

2

u/xr51z 1d ago

[LANGUAGE: Julia]

paste

Part 1 was doable, mostly a lot of lines to write. Ironically I struggled most with what I thought was going to be the easy part, which was divining a number system behind the possible button presses.

Part 2 had me thinking for over an hour, but once it clicked, writing the code was trivial.

2

u/theMachine0094 1d ago edited 1d ago

[LANGUAGE: Rust]

Pretty sure this is as fast as I can make it. Runs in around ~1ms on a 5 year old CPU. Any ideas to make it faster are welcome :)

topaz paste link

→ More replies (8)

2

u/ArmadilloSuch411 1d ago

[LANGUAGE: Python]

code

what I did is just check every possible combinations of 1-2-3 instructions for part1, then for part2 I did bfs to check which number could actually be reached. Nothing fancy, but it works.

2

u/DarkVoidG 1d ago edited 1d ago

[LANGUAGE: Python]

Pretty "straightforward" approach, but it solves this in reasonable time (computes both parts in about 0.2s) so all good.

Edit: Apparently I somehow didn't notice it was BFS, so I used a frontier to keep track of already visited results. Computing time lowered to about 25ms.

Solution in repo

2

u/chkas 1d ago

[LANGUAGE: Easylang]

Solution

2

u/PTVoobaf 1d ago

[LANGUAGE: PowerShell]

Day 5 part 1:

Function Build-Expression {
    [CmdletBinding()]
    param([string]$Button)
    switch -Regex ($Button) {
        '^\d$' { $A = [int]$Button; $Expr = "`$N * 10 + $A" }
        '^\*\d$' { $A = $Button.TrimStart('*'); $Expr = "`$N * $A" }
        '^/\d$' { $A = $Button.TrimStart('/'); $Expr = "[uint][Math]::Floor(`$N / $A)" }
        '^\d->\d$' { $A, $B = $Button -split '->'; $Expr = "[uint]([string]`$N -replace '$A', '$B')" }
        '^oct$' { $Expr = "[uint][Convert]::ToString(`$N, 8)" }
        '^bksp$' { $Expr = "[uint][Math]::Floor(`$N / 10)" }
        default { throw "Unable to parse: $Button" }
    }
    return $Expr
}

Function Build-ButtonExpressions {
    [CmdletBinding()]
    param([string]$Buttons)
    $ButtList = -split $Buttons
    $ButtList = $ButtList | ForEach-Object { $_.Trim('[', ']') }
    $Exprs = $ButtList | ForEach-Object { Build-Expression $_ }
    return $Exprs
}

Function Find-ButtonTargets {
    [CmdletBinding()]
    param([int]$MaxPressed, [string[]]$Expressions)
    $Found = [System.Collections.Generic.HashSet[uint]]::new()
    $State = 0  # initial state
    [void]$Found.Add(0)  # no buttons pressed
    for ($p = 1; $p -le $MaxPressed; $p++) {
        $NewStates = @()
        foreach ($State in $Found) {
            foreach ($E in $Expressions) {
                # press that button to see what happens
                $N = $State
                $NewStates += , (Invoke-Expression $E)
            }
        }
        # record each new state
        foreach ($State in $NewStates) {
            [void]$Found.Add($State)
        }
    }
    # add together all the found number states
    $FoundSum = 0
    foreach ($State in $Found) {
        $FoundSum += $State
    }
    return $FoundSum
}

#$Inp = "[9] [*9] [/2] [1->9] [oct] [bksp]"
$Inp = Get-Content .\05input.txt

$Total = Find-ButtonTargets 3 (Build-ButtonExpressions $Inp)
Write-Output $Total

I had fun figuring out how to make individual Invoke-Expression simulators for each button.

2

u/Prof-Math 1d ago

[Language: Haskell]

I was travelling and racing (both disjoint) so, I took the laziest approach that would work in reasonable time:

import Data.Char (digitToInt, intToDigit)
import Data.List (nub, sort)

--
 [0->2] [bksp] [4] [oct] [1->9] [/2] [*8] [*5] [9]

f0 = id
f1 :: Int -> Int
f1 x = read (go (show x)) where
    go "" = ""
    go (x:xs) = if x == '0' then '2' : go xs else x : go xs


f2 :: Int -> Int
f2 x = (\x -> if x == "" then 0 else read x) (init (show x))


f3 :: Int -> Int
f3 x = read (show x ++ "4")


f4 :: Int -> Int
f4 x = read (reverse (map intToDigit (go x))) where
    go x = if x `div` 8 == 0 then [x] else (x `mod` 8) : (go (x `div` 8))



f5 :: Int -> Int
f5 x = read (go (show x)) where
    go "" = ""
    go (x:xs) = if x == '1' then '9' : go xs else x : go xs


f6 x = x `div` 2


f7 x = x * 8


f8 x = x * 5


f9 :: Int -> Int
f9 x = read (show x ++ "9")


solve fs = sum (nub [(a.b.c) 0 | a <- fs, b <- fs, c <- fs])


every :: [Int -> Int] -> [Int] -> [Int]
every fs lis = let l2 = sort (nub [y | f <- fs, x <- lis, let k = if f x >= 10000 then x else f x, y <- [k, x]]) in if lis == l2 then lis else every fs l2

solve2 fs = sum (every fs [0])

2

u/maitre_lld 1d ago

[Language: Ocaml]
https://github.com/MeisterLLD/aoc2026/blob/main/day5.ml

Uses Ocaml 5.5 additions to the String module.

Around 40ms for both parts.

2

u/_tfa 1d ago edited 1d ago

[Language: Ruby]

ops = File.read("input.txt").split.map do |op|
    num = op[/\d/].to_i
    case op
        when /\[\d\]/     then ->(z) { z*10 + num }
        when /\[\*\d\]/   then ->(z) { z * num }
        when /\[\/\d\]/   then ->(z) { z / num }
        when /\[\d->\d\]/ then ->(z) { z.to_s.gsub(op[1], op[4]).to_i }
        when "[oct]"      then ->(z) { z.to_s(8).to_i }
        when "[bksp]"     then ->(z) { z / 10 }
    end     
end
result = (1..3).flat_map{|c| ops.repeated_permutation(c)
                                .map{|t| t.inject(0){|a,e| e.(a) }}}
                                .uniq
                                .sum
puts "Part 1: #{result}"

visited = Set[0]
queue = [0]

until queue.empty?
  value = queue.pop
  ops.each do |op|
    nextval = op.(value)     
    nextval = value if nextval > 9999
      
    next if visited.include?(nextval)

    visited << nextval
    queue << nextval
  end
end
puts "Part 2: #{visited.sum}"