56 lines
1.4 KiB
Rust
56 lines
1.4 KiB
Rust
//! Day 07 of 2021.
|
|
|
|
use crate::prelude::*;
|
|
|
|
/// Get the solution for day 07 of 2021.
|
|
pub fn solution() -> Solution {
|
|
Solution::new(Day::new(7, 2021), part_1, part_2)
|
|
.with_expected(328318, 89791146)
|
|
}
|
|
|
|
/// Parse the list and highest number of crabs from the puzzle input.
|
|
fn parse_crabs(input: &str) -> Result<(Vec<isize>, isize)> {
|
|
let crabs = input
|
|
.split(',')
|
|
.map(str::parse)
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
let highest_crab = *crabs
|
|
.iter()
|
|
.max()
|
|
.ok_or_else(|| eyre!("Unable to find highest crab"))?;
|
|
|
|
Ok((crabs, highest_crab))
|
|
}
|
|
|
|
/// The logic to solve part one.
|
|
fn part_1(input: &str) -> Result<String> {
|
|
let (crabs, highest_crab) = parse_crabs(input)?;
|
|
(0..=highest_crab)
|
|
.map(|target_position| {
|
|
crabs
|
|
.iter()
|
|
.map(|crab| (target_position - crab).abs())
|
|
.sum::<isize>()
|
|
})
|
|
.min()
|
|
.map(|result| result.to_string())
|
|
.ok_or_else(|| eyre!("Unable to find lowest fuel"))
|
|
}
|
|
|
|
/// The logic to solve part two.
|
|
fn part_2(input: &str) -> Result<String> {
|
|
let (crabs, highest_crab) = parse_crabs(input)?;
|
|
(0..=highest_crab)
|
|
.map(|target_position| {
|
|
crabs
|
|
.iter()
|
|
.map(|crab| (target_position - crab).abs())
|
|
.map(|steps| (steps * (steps + 1)) / 2)
|
|
.sum::<isize>()
|
|
})
|
|
.min()
|
|
.map(|result| result.to_string())
|
|
.ok_or_else(|| eyre!("Unable to find lowest fuel"))
|
|
}
|