
Source: Day 1: Dusty Shed
Full solution for today (spoilers!).
Part 1
Given a list of integers, calculate the product of the most common three values.
Okay, first the direct way of doing it.
We’ll create a vec that contains a count for each value, dynamically expanding it so that we have enough counts. Partially, we can get away with this since, looking at the input, we only have 3 digit values so at most we’ll have 1000. We could probably even pre-allocate this.
Then, sort the list and multiply the first 3.
#[aoc::register]
fn part1(input: &str) -> impl Into<String> {
let mut counts = vec![];
for line in input.lines() {
if line.trim().is_empty() {
continue;
}
let index = line.parse::<usize>().unwrap();
if index >= counts.len() {
counts.resize(index + 1, 0);
}
counts[index] += 1;
}
let mut indexed_counts = counts.iter().enumerate().collect::<Vec<_>>();
indexed_counts.sort_by(|a, b| b.1.cmp(a.1));
(indexed_counts[0].0 * indexed_counts[1].0 * indexed_counts[2].0).to_string()
}
There are a few other ways we could write that though.
First option, let’s do it with a HashMap (specifically fxhash, since we prefer speed over cryptographic safety):
#[aoc::register]
fn part1_hash(input: &str) -> impl Into<String> {
let mut counts = FxHashMap::default();
for line in input.lines() {
if line.trim().is_empty() {
continue;
}
let index = line.parse::<usize>().unwrap();
*counts.entry(index).or_insert(0) += 1;
}
let mut indexed_counts = counts.iter().collect::<Vec<_>>();
indexed_counts.sort_by(|a, b| b.1.cmp(a.1));
(indexed_counts[0].0 * indexed_counts[1].0 * indexed_counts[2].0).to_string()
}
One thing we’ll run into these two is that we’re allocating two copies of the list: the initial counts and the sorted version. But we really don’t need to do that. Since we only need 3 values, we can only track those:
#[aoc::register]
fn part1_nocopy(input: &str) -> impl Into<String> {
let mut counts = vec![];
for line in input.lines() {
if line.trim().is_empty() {
continue;
}
let index = line.parse::<usize>().unwrap();
if index >= counts.len() {
counts.resize(index + 1, 0);
}
counts[index] += 1;
}
let mut maxkey = [0, 0, 0];
let mut maxval = [0, 0, 0];
for (key, &val) in counts.iter().enumerate() {
for i in 0..3 {
if val > maxval[i] {
for j in (i + 1..3).rev() {
maxval[j] = maxval[j - 1];
maxkey[j] = maxkey[j - 1];
}
maxval[i] = val;
maxkey[i] = key;
break;
}
}
}
(maxkey[0] * maxkey[1] * maxkey[2]).to_string()
}
And finally, let’s go back to my programming roots a bit. Let’s just do it (more or less) functionally 😄.
#[aoc::register]
fn part1_fn(input: &str) -> impl Into<String> {
input
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| line.parse::<usize>().unwrap())
.counts()
.into_iter()
.sorted_by(|a, b| b.1.cmp(&a.1))
.take(3)
.map(|(k, _)| k)
.product::<usize>()
.to_string()
}
I do like how relatively clean that is, but it’s up to you if that’s actually easier to read than the first version or not.
They do all find the same answer though, which is always a good sign!
$ just run 1
part1: 76923790
part1_fn: 76923790
part1_hash: 76923790
part1_nocopy: 76923790
The benchmarks are about what I’d expect too:
$ just bench 1
part1: 27.717µs ± 1.684µs [min: 25.416µs, max: 34.709µs, median: 27.833µs]
part1_fn: 71.92µs ± 2.176µs [min: 66.458µs, max: 78.917µs, median: 72.208µs]
part1_hash: 33.176µs ± 870ns [min: 31.708µs, max: 37.75µs, median: 33.375µs]
part1_nocopy: 21.666µs ± 517ns [min: 21.292µs, max: 24.709µs, median: 21.459µs]
In this case, nocopy is the fastest, since it’s avoiding the second allocation, then just the vec. hash is a bit slower, but if we were using the std::collections::HashMap that would be much slower–kind of exactly like fn is. Behind the scenes .counts() is creating a HashMap.
Still. They’re all measured in µs. So… this is really not something that we need to optimize more.
Part 2
Find the product of the 3 least common values.
This is mostly interesting since we need the 3 least common values that exist. So for the vec solution, we need to specifically filter out zeros:
#[aoc::register]
fn part2(input: &str) -> impl Into<String> {
let mut counts = vec![];
for line in input.lines() {
if line.trim().is_empty() {
continue;
}
let index = line.parse::<usize>().unwrap();
if index >= counts.len() {
counts.resize(index + 1, 0);
}
counts[index] += 1;
}
let mut indexed_counts = counts.iter().enumerate().collect::<Vec<_>>();
indexed_counts.sort_by(|a, b| a.1.cmp(b.1));
indexed_counts.retain(|&(_, &count)| count != 0);
(indexed_counts[0].0 * indexed_counts[1].0 * indexed_counts[2].0).to_string()
}
#[aoc::register]
fn part2_hash(input: &str) -> impl Into<String> {
let mut counts = FxHashMap::default();
for line in input.lines() {
if line.trim().is_empty() {
continue;
}
let index = line.parse::<usize>().unwrap();
*counts.entry(index).or_insert(0) += 1;
}
let mut indexed_counts = counts.iter().collect::<Vec<_>>();
indexed_counts.sort_by(|a, b| a.1.cmp(b.1));
(indexed_counts[0].0 * indexed_counts[1].0 * indexed_counts[2].0).to_string()
}
In both cases, we are reversing the sort by a.cmp(b) instead of b.cmp(a). But for the hash version, we don’t need to filter, since we only have keys that have at least one value in the map in the first place.
$ just run 1
part2: 117046800
part2_hash: 117046800
$ just bench 1
part2: 31.762µs ± 3.647µs [min: 29.291µs, max: 49.208µs, median: 30.333µs]
part2_hash: 34.736µs ± 8.167µs [min: 30.916µs, max: 108.625µs, median: 32.167µs]
Cool.
Visualization
I did make a quick visualization showing the heights as they’re loaded with the 3 highest in red and their heights in the top right.
Not really the most interesting thing, I suppose. So it goes. Only so much to work with here.
Benchmarks
$ just bench 1
part1: 27.717µs ± 1.684µs [min: 25.416µs, max: 34.709µs, median: 27.833µs]
part1_fn: 71.92µs ± 2.176µs [min: 66.458µs, max: 78.917µs, median: 72.208µs]
part1_hash: 33.176µs ± 870ns [min: 31.708µs, max: 37.75µs, median: 33.375µs]
part1_nocopy: 21.666µs ± 517ns [min: 21.292µs, max: 24.709µs, median: 21.459µs]
part2: 31.762µs ± 3.647µs [min: 29.291µs, max: 49.208µs, median: 30.333µs]
part2_hash: 34.736µs ± 8.167µs [min: 30.916µs, max: 108.625µs, median: 32.167µs]