
Source: Day 5: Rhythmic Factory
Full solution for today (spoilers!).
Part 1
You are given a calculator with a custom set of buttons. What is the sum of all values that can be reached from 0 in up to 3 button presses?
[A]appends the digit A[*A]multiplies by A[/A]divides by A (integer division)[A->B]replaces all digit A with digit B[oct]convert the number to octal (then treat that as a new decimal value)[bksp]remove the rightmost digit (0 stays 0)
So we basically have a virtual machine! I do love a good virtual machine.
First, the representation and parser:
#[derive(Copy, Clone, Debug)]
enum Button {
Append(usize),
Multiply(usize),
Divide(usize),
Convert(char, char),
Octal,
Backspace,
}
impl From<&str> for Button {
fn from(value: &str) -> Self {
if value == "oct" {
Button::Octal
} else if value == "bksp" {
Button::Backspace
} else if value.starts_with('*') {
Button::Multiply(value.strip_prefix('*').unwrap().parse().unwrap())
} else if value.starts_with('/') {
Button::Divide(value.strip_prefix('/').unwrap().parse().unwrap())
} else if value.len() == 4 {
let chars = value.as_bytes();
Button::Convert(chars[0] as char, chars[3] as char)
} else {
Button::Append(value.parse().unwrap())
}
}
}
And then a function to apply each button:
impl Button {
fn apply(&self, input: usize) -> usize {
match self {
Button::Append(v) => input * 10 + v,
Button::Multiply(v) => input * v,
Button::Divide(v) => input / v,
Button::Convert(a, b) => input
.to_string()
.chars()
.map(|c| if c == *a { *b } else { c })
.collect::<String>()
.parse()
.unwrap(),
Button::Octal => format!("{input:o}").parse().unwrap(),
Button::Backspace => input / 10,
}
}
}
I’m not super thrilled with how Convert is done, but really, I’m not sure how to do it better. Perhaps it would be better to keep the internal state as a string/list of digits and do multiplication/division ourselves?
In any case, this means part 1 is:
#[aoc::register]
fn part1(input: &str) -> impl Into<String> {
let buttons: Vec<Button> = input
.split_ascii_whitespace()
.map(|b| {
b.strip_prefix('[')
.unwrap()
.strip_suffix(']')
.unwrap()
.into()
})
.collect();
let mut values = fxhash::FxHashSet::default();
for b1 in buttons.iter() {
for b2 in buttons.iter() {
for b3 in buttons.iter() {
let result = b3.apply(b2.apply(b1.apply(0)));
if !values.contains(&result) {
log::debug!("{b1:?} {b2:?} {b3:?} -> {result}");
}
values.insert(result);
}
}
}
values.iter().sum::<usize>().to_string()
}
One neat thing about that is that because we are storing the values as a HashSet, we don’t really have to worry about multiple ways to make the same value. It just works(tm).
We could also write this a slightly different way, starting with 0 as the only value you can generate with zero presses, then expand that into all values that can be generated with 0 or 1 presses, then with 0-2, then finally 0-3:
#[aoc::register]
fn part1_expand(input: &str) -> impl Into<String> {
let buttons: Vec<Button> = input
.split_ascii_whitespace()
.map(|b| {
b.strip_prefix('[')
.unwrap()
.strip_suffix(']')
.unwrap()
.into()
})
.collect();
let mut values = fxhash::FxHashSet::default();
values.insert(0);
for _ in 0..3 {
let new_values = values
.iter()
.flat_map(|v| buttons.iter().map(|b| b.apply(*v)))
.collect::<fxhash::FxHashSet<usize>>();
values.extend(new_values);
}
values.iter().sum::<usize>().to_string()
}
Which, because you’re only iterating the set of generated values rather than every single button combination ends up being a bit faster:
$ just run 5
part1: 26902
part1_expand: 26902
$ just bench 5
part1: 38.568µs ± 5.366µs [min: 33.916µs, max: 56.583µs, median: 35.75µs]
part1_expand: 6.597µs ± 423ns [min: 5.833µs, max: 8.209µs, median: 6.666µs]
Not too bad.
Part 2
What is the sum of all possible values that can be generated with any number of button presses… such that the current/final value never exceeds 4 digits?
The slight difference this time is that we can store either a hashset (as before) or just by creating a [bool; 10000].
#[aoc::register]
fn part2(input: &str) -> impl Into<String> {
let buttons: Vec<Button> = input
.split_ascii_whitespace()
.map(|b| {
b.strip_prefix('[')
.unwrap()
.strip_suffix(']')
.unwrap()
.into()
})
.collect();
let mut values = [false; 10000];
values[0] = true;
loop {
let mut changed = false;
for b in buttons.iter() {
for i in 0..10000 {
if values[i] {
let r = b.apply(i);
if r < 10000 && !values[r] {
values[r] = true;
changed = true;
}
}
}
}
if !changed {
break;
}
}
values
.iter()
.enumerate()
.flat_map(|(i, b)| if *b { Some(i) } else { None })
.sum::<usize>()
.to_string()
}
#[aoc::register]
fn part2_hash(input: &str) -> impl Into<String> {
let buttons: Vec<Button> = input
.split_ascii_whitespace()
.map(|b| {
b.strip_prefix('[')
.unwrap()
.strip_suffix(']')
.unwrap()
.into()
})
.collect();
let mut values = fxhash::FxHashSet::default();
values.insert(0);
loop {
let mut changed = false;
for b in buttons.iter() {
let mut new_values = fxhash::FxHashSet::default();
for i in values.iter() {
let r = b.apply(*i);
if r < 10000 && !values.contains(&r) {
new_values.insert(r);
changed = true;
}
}
values.extend(new_values.iter());
}
if !changed {
break;
}
}
values
.iter()
.sum::<usize>()
.to_string()
}
The problem with the hashset in the second example is, because we can’t modify the set of values while we’re iterating it in each generation, we have to allocate a new hashset. Still, it’s not that difference performance wise.
$ just run 5
part2: 42615836
part2_hash: 42615836
$ just bench 5
part2: 5.025478ms ± 111.615µs [min: 4.712834ms, max: 5.327458ms, median: 5.01425ms]
part2_hash: 7.520439ms ± 89.884µs [min: 7.210292ms, max: 7.704625ms, median: 7.521417ms]
Visualization
I did have a little fun visualizing part 2 of this problem. Here is a grid of all 10,000 values as a 100x100 array. Each cell is colored in as soon as we’ve figured out a way to do it.
First, we have a color for which button was the last one pressed to get to that color:
And here we have which ‘generation’ (first) added it:
Benchmarks
$ just bench 5
part1: 41.987µs ± 4.458µs [min: 37.458µs, max: 52.916µs, median: 39.542µs]
part1_expand: 6.687µs ± 137ns [min: 6.541µs, max: 7.875µs, median: 6.667µs]
part2: 5.025478ms ± 111.615µs [min: 4.712834ms, max: 5.327458ms, median: 5.01425ms]
part2_hash: 7.520439ms ± 89.884µs [min: 7.210292ms, max: 7.704625ms, median: 7.521417ms]