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

50 lines
1.2 KiB
Rust
Raw Normal View History

2021-12-07 13:24:37 +00:00
use color_eyre::{eyre::eyre, Result};
pub fn solve() -> Result<()> {
let input_data = include_str!("../../data/day_07.txt").trim();
println!("Day 07 Part 1: {}", part_1(input_data)?);
println!("Day 07 Part 2: {}", part_2(input_data)?);
Ok(())
}
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(eyre!("Unable to find highest crab"))?;
Ok((crabs, highest_crab))
}
fn part_1(input: &str) -> Result<isize> {
let (crabs, highest_crab) = parse_crabs(input)?;
(0..=highest_crab)
.map(|target_position| {
crabs
.iter()
.map(|crab| (target_position - crab).abs())
.sum()
})
.min()
.ok_or(eyre!("Unable to find lowest fuel"))
}
fn part_2(input: &str) -> Result<isize> {
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()
})
.min()
.ok_or(eyre!("Unable to find lowest fuel"))
}