1
Fork 0
advent-of-code/source/year_2021/day_07/mod.rs

50 lines
1.2 KiB
Rust
Raw Normal View History

use crate::prelude::*;
2021-12-07 13:24:37 +00:00
pub fn solution() -> Solution {
Solution::new(Day::new(7, 2021), part_1, part_2)
.with_expected(328318, 89791146)
2021-12-07 13:24:37 +00:00
}
fn parse_crabs(input: &str) -> Result<(Vec<isize>, isize)> {
let crabs = input
.split(',')
2021-12-07 13:24:37 +00:00
.map(str::parse)
.collect::<Result<Vec<_>, _>>()?;
let highest_crab = *crabs
.iter()
.max()
.ok_or_else(|| eyre!("Unable to find highest crab"))?;
2021-12-07 13:24:37 +00:00
Ok((crabs, highest_crab))
}
fn part_1(input: &str) -> Result<String> {
2021-12-07 13:24:37 +00:00
let (crabs, highest_crab) = parse_crabs(input)?;
(0..=highest_crab)
.map(|target_position| {
crabs
.iter()
.map(|crab| (target_position - crab).abs())
.sum::<isize>()
2021-12-07 13:24:37 +00:00
})
.min()
.map(|result| result.to_string())
.ok_or_else(|| eyre!("Unable to find lowest fuel"))
2021-12-07 13:24:37 +00:00
}
fn part_2(input: &str) -> Result<String> {
2021-12-07 13:24:37 +00:00
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>()
2021-12-07 13:24:37 +00:00
})
.min()
.map(|result| result.to_string())
.ok_or_else(|| eyre!("Unable to find lowest fuel"))
2021-12-07 13:24:37 +00:00
}