Nime
Metadata
Table of contents

Advent of Code 2026 Day 5

Day 5: Rhythmic Factory

https://adventofcode.com/2026/day/5

CHOO, CHOO! The train arrives at a manufacturing facility.

You become interested in a “fancy” microwave some elves are gathered around. (The barrels of magic smoke all around the facility? BORING. Microwaves!)

There is a number on the screen that starts at 0. Each button transforms the number it currently shows.

Todays input is a list of the buttons.

An example input looks like this:

input.txt
[9] [*9] [/2] [1->9] [oct] [bksp]

There are six kinds of buttons:

  1. [A] appends digit A (replacing 0 if that’s what’s shown).
  2. [*A] multiplies the value by A.
  3. [/A] integer-divides the value by A (rounded down).
  4. [A->B] replaces every occurrence of A in the displayed value with B.
  5. [oct] converts the number to base-8 digits (123 -> octal 173).
  6. [bksp] drops the last digit (it becomes 0 when operating on a single-digit).

Parsing

I strip the surrounding square brackets from each token and turn it into a Button.

day_05.rs
#[derive(Clone, Copy)]
enum Button {
Append(u32),
Mul(u32),
Div(u32),
Replace(u32, u32),
Oct,
Bksp,
}
fn parse(input: &str) -> Vec<Button> {
input
.split_ascii_whitespace()
.map(|tok| match tok.trim_matches(['[', ']']) {
"oct" => Button::Oct,
"bksp" => Button::Bksp,
s if s.starts_with('*') => Button::Mul(s[1..].parse().unwrap()),
s if s.starts_with('/') => Button::Div(s[1..].parse().unwrap()),
s if s.contains("->") => {
let (a, b) = s.split_once("->").unwrap();
Button::Replace(a.parse().unwrap(), b.parse().unwrap())
}
s => Button::Append(s.parse().unwrap()),
})
.collect()
}

Helpers

I created a helper function that can apply a Button press given the current number on the screen.

For Oct, I peel off base-8 digits with % 8 and / 8, placing each digit in its base-10 column (1, 10, 100, …). Since 0 has no non-zero octal digits, starting at 0 skips the while n > 0 loop and returns 0.

For Replace, I peel off base-10 digits with % 10 and / 10 and swap A for B. If val starts at 0, the while n > 0 loop wouldn’t run, so I handle val == 0 upfront (B if from == 0, else 0).

day_05.rs
fn press(button: Button, val: u32) -> u32 {
match button {
Button::Append(d) => val * 10 + d,
Button::Mul(n) => val * n,
Button::Div(n) => val / n,
Button::Bksp => val / 10,
Button::Oct => {
let mut n = val;
let mut res = 0;
let mut place = 1;
while n > 0 {
res += (n % 8) * place;
n /= 8;
place *= 10;
}
res
}
Button::Replace(from, to) => {
if val == 0 {
return if from == 0 { to } else { 0 };
}
let mut n = val;
let mut res = 0;
let mut place = 1;
while n > 0 {
let digit = n % 10;
res += if digit == from { to } else { digit } * place;
n /= 10;
place *= 10;
}
res
}
}
}

Part 1

The question asks for the sum of every number reachable in at most three button presses.

Every button press is one step from 0, so breadth-first search (BFS) visits states in order of press count (0, then 1, 2, 3). Each state is a pair of (value, steps).

I start off the BFS by seeding the queue with (0, 0), screen shows 0 and 0 buttons were pressed.

Once steps == 3, I skip expanding that state further. visited.insert(next) ensures each reached number is queued and summed once. It adds next to visited and returns true if it wasn’t already present.

day_05.rs
use std::collections::{HashSet, VecDeque};
pub fn part_1(input: &str) -> u64 {
let buttons = parse(input);
let mut visited = HashSet::from([0]);
let mut queue = VecDeque::from([(0, 0)]);
while let Some((val, steps)) = queue.pop_front() {
if steps == 3 {
continue;
}
for &btn in &buttons {
let next = press(btn, val);
if visited.insert(next) {
queue.push_back((next, steps + 1));
}
}
}
visited.into_iter().map(u64::from).sum()
}

Part 2

The question asks for the sum of every number reachable in any number of button presses.

The screen only has 4 digits, so the maximum value is 9999. Pressing buttons that would result in a larger number do nothing.

I drop the steps counter and only enqueue results where next <= 9999 and visited.insert(next) is true. Even with cycles like [*9] and [/9], there are at most 10,000 possible screen values, so the loop always finishes.

day_05.rs
use std::collections::{HashSet, VecDeque};
pub fn part_2(input: &str) -> u64 {
let buttons = parse(input);
let mut visited = HashSet::from([0_u32]);
let mut queue = VecDeque::from([0_u32]);
while let Some(val) = queue.pop_front() {
for &btn in &buttons {
let next = press(btn, val);
if next <= 9999 && visited.insert(next) {
queue.push_back(next);
}
}
}
visited.into_iter().map(u64::from).sum()
}

Final code

Both parts are very similar, so I combined them.

day_05.rs
use std::collections::{HashSet, VecDeque};
#[derive(Clone, Copy)]
enum Button {
Append(u32),
Mul(u32),
Div(u32),
Replace(u32, u32),
Oct,
Bksp,
}
fn press(button: Button, val: u32) -> u32 {
match button {
Button::Append(d) => val * 10 + d,
Button::Mul(n) => val * n,
Button::Div(n) => val / n,
Button::Bksp => val / 10,
Button::Oct => {
let mut n = val;
let mut res = 0;
let mut place = 1;
while n > 0 {
res += (n % 8) * place;
n /= 8;
place *= 10;
}
res
}
Button::Replace(from, to) => {
if val == 0 {
return if from == 0 { to } else { 0 };
}
let mut n = val;
let mut res = 0;
let mut place = 1;
while n > 0 {
let digit = n % 10;
res += if digit == from { to } else { digit } * place;
n /= 10;
place *= 10;
}
res
}
}
}
fn parse(input: &str) -> Vec<Button> {
input
.split_ascii_whitespace()
.map(|tok| match tok.trim_matches(['[', ']']) {
"oct" => Button::Oct,
"bksp" => Button::Bksp,
s if s.starts_with('*') => Button::Mul(s[1..].parse().unwrap()),
s if s.starts_with('/') => Button::Div(s[1..].parse().unwrap()),
s if s.contains("->") => {
let (a, b) = s.split_once("->").unwrap();
Button::Replace(a.parse().unwrap(), b.parse().unwrap())
}
s => Button::Append(s.parse().unwrap()),
})
.collect()
}
fn sum_reachable(buttons: &[Button], max_steps: Option<usize>, max_val: Option<u32>) -> u64 {
let mut visited = HashSet::from([0]);
let mut queue = VecDeque::from([(0, 0)]);
while let Some((val, steps)) = queue.pop_front() {
if max_steps.is_some_and(|limit| steps == limit) {
continue;
}
for &btn in buttons {
let next = press(btn, val);
if max_val.is_some_and(|cap| next > cap) {
continue;
}
if visited.insert(next) {
queue.push_back((next, steps + 1));
}
}
}
visited.into_iter().map(u64::from).sum()
}
pub fn part_1(input: &str) -> u64 {
sum_reachable(&parse(input), Some(3), None)
}
pub fn part_2(input: &str) -> u64 {
sum_reachable(&parse(input), None, Some(9999))
}