From 509f796a52c67e462e79781ebc26ec4545f5feb2 Mon Sep 17 00:00:00 2001 From: Bauke Date: Tue, 7 Dec 2021 14:24:37 +0100 Subject: [PATCH] Solve day 7! --- source/day_07/mod.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++ source/main.rs | 2 ++ 2 files changed, 51 insertions(+) create mode 100644 source/day_07/mod.rs diff --git a/source/day_07/mod.rs b/source/day_07/mod.rs new file mode 100644 index 0000000..71090f5 --- /dev/null +++ b/source/day_07/mod.rs @@ -0,0 +1,49 @@ +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)> { + let crabs = input + .split(",") + .map(str::parse) + .collect::, _>>()?; + + let highest_crab = *crabs + .iter() + .max() + .ok_or(eyre!("Unable to find highest crab"))?; + + Ok((crabs, highest_crab)) +} + +fn part_1(input: &str) -> Result { + 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 { + 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")) +} diff --git a/source/main.rs b/source/main.rs index bcad1e2..baef111 100644 --- a/source/main.rs +++ b/source/main.rs @@ -8,6 +8,7 @@ mod day_03; mod day_04; mod day_05; mod day_06; +mod day_07; fn main() -> Result<()> { color_eyre::install()?; @@ -21,6 +22,7 @@ fn main() -> Result<()> { day_04::solve, day_05::solve, day_06::solve, + day_07::solve, ]; for day in days {