Josiah Winslow solves Advent of Code

Rhythmic Factory

Published: 2026-12-05 Original Prompt

Part 1

We’re trying to operate a fancy microwave with unusual buttons — like [*9] and [/2] — and see which cooking times we can reach with up to three button presses. Just when you thought you wouldn’t use math in your day-to-day life…

Each time we press a button, it changes the value on the microwave’s screen in some strange way. This makes each button almost act like its own function, which takes a number and returns some transformed version of that number; for example, [*9] would take a number n and return n * 9. You could think of writing some function or lambda expression for it, such as lambda n: n * 9, and then calling that on a value in order to change it.

In fact, this gave me an idea: why not literally do that? We could represent each button as a function, and then pressing buttons would be like calling functions. It’s a more functional programming-like style than many programmers are used to, but it’s worth a shot.

First, let’s extract all the labels of the buttons (which are within brackets, e.g. [1->9]) so we can operate on just the labels. We’ll use these labels as hints for how to create the button functions.

2026\day05\solution.py
from collections.abc import Callable
type Button = Callable[[int], int]
def parse_buttons(text: str) -> list[Button]:
# Brackets are around each label, so strip them first
return [create_button(label[1:-1]) for label in text.split()]

Now to actually figure out how to create a button function for each kind of label. The place I’ll be creating these button functions is in another function — which makes it a higher-order function, because it’s a function that returns functions.

Rather than a big if-elif-else chain, it’ll be more beautiful in my opinion to use the match statement. Here’s how you’d use it to create a case for each button type; I’ve ordered the cases this way to make them go from most specific to least specific, as is best practice when using match.

2026\day05\solution.py
def create_button(label: str) -> Button:
"""
Return a function that simulates pressing the button with the
provided label.
"""
match label:
# [oct]: convert to octal
case "oct":
...
# [bksp]: backspace
case "bksp":
...
# [*A]: multiply by A
case st if st.startswith("*"):
...
# [/A]: divide by A
case st if st.startswith("/"):
...
# [A->B]: replace A with B
case st if "->" in st:
...
# [A]: append A
case st if st.isdigit():
...
# Any other label
case _:
raise ValueError(f"invalid button label: {label}")

Some of these cases will have us treat the numeric value like an int, and others will have us treat it like a str; this is fine, as long as we remember to make all of the necessary conversions between them, and we ultimately return an int value each time. Let’s go over the implementations of each case — remembering that each case will return its own function, which we create using the lambda keyword.

The hard part is over, and we can now get to finding the values that are reachable with up to three button presses. We can use itertools.product() to get all possible button sequences of a certain length, and — like I said from the very beginning — each button can be pressed by calling it and passing in the current value. We can then collect each value we reach into a set called reachable, and sum them up to get our answer.

2026\day05\solution.py
from itertools import product
...
class Solution(TextSolution):
def part_1(self) -> int:
buttons = parse_buttons(self.input)
reachable: set[int] = set()
for num_presses in range(4): # From 0 to 3 presses
for button_sequence in product(buttons, repeat=num_presses):
# Press each button one after another
value = 0
for button in button_sequence:
value = button(value)
# Mark the resulting value as reachable
reachable.add(value)
return sum(reachable)

And just like that, we’ve got a solution that runs in less time than it takes to melt butter in the microwave. (Even a fancy one!)

Part 2

Now that we have a programmatic model of the fancy microwave, which numeric values can we make with any sequence of buttons? The naive approach would be to increase the repeat parameter we give to itertools.product() (in addition to the other necessary changes)… but this will quickly blow up in runtime the longer the button sequences get.

Instead, the right approach here seems to be breadth-first search. We can explore the consequences of pressing each button starting from 0, and save the unseen resulting values in a queue to try continuing from later; then we can explore pressing each button starting from each of those values and save the unseen results for later, and so on until we stop reaching resulting values we haven’t seen. This search approach is made most efficient using collections.deque(), which allows us to continually remove items from one end and add items to the other end.

The search will start with a value of 0, which is reachable with zero button presses. The unseen-values deque will also start with a value of 0.

2026\day05\solution.py
from collections import deque
...
class Solution(TextSolution):
...
def part_2(self) -> int:
buttons = parse_buttons(self.input)
# 0 is reachable with zero presses
reachable: set[int] = {0}
unseen = deque(reachable)
...

Each iteration of the search starts by popping a starting value from the left of the deque. We then go deeper by attempting to press each button starting from that value. And if we get a resulting value that we haven’t yet seen in the reachable set, we add it to the set and append it to the unseen-values deque for later. This continues until we have no more unseen values left to try.

(Oh, and don’t forget: our fancy microwave can’t display more than 4 digits at a time, so any presses that bring the resulting value above 9999 do nothing and should be ignored.)

2026\day05\solution.py
...
# NOTE The microwave ignores presses that produce more than 4 digits
MAX_VALUE = 9999
...
class Solution(TextSolution):
...
def part_2(self) -> int:
...
while unseen:
value = unseen.popleft()
for button in buttons:
# Do nothing for resulting values that are too large
if (result := button(value)) > MAX_VALUE:
continue
# If this resulting value is new, mark it as reachable
# and not yet seen
if result not in reachable:
reachable.add(result)
unseen.append(result)
return sum(reachable)

This process is enough to give us an answer on its own. In fact, with a few small tweaks, it can actually help us solve Part 1 as well! Let me explain… hopefully in less time than it takes to microwave a Hot Pocket.


First, let’s retool our breadth-first search to store not only the unseen values in the deque, but also the number of presses it took to get there (with 0 taking zero presses). This requires a bit more bookkeeping — including adding 1 to the number of presses whenever we reach a new result — but it’s not too bad.

2026\day05\solution.py
...
class Solution(TextSolution):
def solve(self) -> tuple[int, int]:
buttons = parse_buttons(self.input)
# 0 is reachable with zero presses
reachable: dict[int, int] = {0: 0} # value: num_presses
unseen = deque(reachable.items())
while unseen:
value, num_presses = unseen.popleft()
for button in buttons:
# Do nothing for resulting values that are too large
if (result := button(value)) > MAX_VALUE:
continue
# If this resulting value is new, mark it as reachable
# in one more press and not yet seen
if result not in reachable:
reachable[result] = num_presses + 1
unseen.append((result, num_presses + 1))
...

A breadth-first search will go forward by one depth level on each iteration, and all items at a certain depth will be explored before any items one level deeper. Because of this, we know that the first time we encounter a microwave value in this search, it will be at the fewest number of presses necessary to display it — and by design, we never encounter it again. This means the button press counts we store for each value are indeed the minimum press counts required for them.

So let’s ask Part 1’s question again: which values can we reach with up to three button presses? We can answer this question with a simple generator expression, now that we have these button press counts stored alongside these values.

2026\day05\solution.py
...
class Solution(TextSolution):
def solve(self) -> tuple[int, int]:
...
reachable_in_up_to_3 = (
value
for value, num_presses in reachable.items()
if num_presses <= 3
)
return sum(reachable_in_up_to_3), sum(reachable)

This allows us to completely eliminate that Part 1 implementation from before!1 Simple is better than complex, indeed. And with that… I think your Hot Pocket is done.

Footnotes

  1. This may raise the question: if we were enforcing MAX_VALUE to keep the value at 4 digits or less fewer in Part 2 but not Part 1, doesn’t that break Part 1 of our unified solution?

    You’d be right to be concerned about that, but it doesn’t happen to matter for this puzzle: the highest value you could conceivably reach with any three button presses is 999 (from pressing [9] three times), which indeed is within the microwave’s digit length cap. ↩