diff --git a/src/lib/solutions/mod.rs b/src/lib/solutions/mod.rs index 9c7a779..079cd5e 100644 --- a/src/lib/solutions/mod.rs +++ b/src/lib/solutions/mod.rs @@ -3,6 +3,7 @@ pub mod year_2020; pub mod year_2021; pub mod year_2022; pub mod year_2023; +pub mod year_2024; type BoxedSolution = Box; type DayAssociations = std::collections::HashMap; @@ -12,6 +13,7 @@ pub fn all_solutions() -> YearAssociations { let associations: Vec<(i32, DayAssociations)> = vec![ (2015, year_2015::solutions()), (2023, year_2023::solutions()), + (2024, year_2024::solutions()), ]; associations.into_iter().collect() } diff --git a/src/lib/solutions/year_2024/day_01.rs b/src/lib/solutions/year_2024/day_01.rs new file mode 100644 index 0000000..ba45f4b --- /dev/null +++ b/src/lib/solutions/year_2024/day_01.rs @@ -0,0 +1,51 @@ +use crate::utils::solution::Solution; +use std::collections::{BinaryHeap, HashMap}; + +/// Puzzle: https://adventofcode.com/2024/day/1 +pub struct Day01 {} + +impl Solution for Day01 { + fn part_one(&self, input: &str) -> Option { + let (left, right) = sorted_lists(input); + Some( + left.iter() + .zip(right.iter()) + .map(|(a, b)| (b - a).abs()) + .sum::() + .to_string(), + ) + } + + fn part_two(&self, input: &str) -> Option { + let (left, right) = sorted_lists(input); + + let counts = right + .iter() + .fold(HashMap::::new(), |mut counts, &value| { + *counts.entry(value).or_insert(0) += 1; + counts + }); + + Some( + left.iter() + .map(|value| value * counts.get(value).unwrap_or(&0)) + .sum::() + .to_string(), + ) + } +} + +fn sorted_lists(input: &str) -> (Vec, Vec) { + let (left, right) = input.lines().fold( + (BinaryHeap::::new(), BinaryHeap::::new()), + |(mut left, mut right), line| { + let (a, b) = line.split_once(" ").expect("Unable to split line at \" \""); + left.push(a.trim().parse::().expect("Bad integer")); + right.push(b.trim().parse::().expect("Bad integer")); + + (left, right) + }, + ); + + (left.into_sorted_vec(), right.into_sorted_vec()) +} diff --git a/src/lib/solutions/year_2024/mod.rs b/src/lib/solutions/year_2024/mod.rs new file mode 100644 index 0000000..eac2e6f --- /dev/null +++ b/src/lib/solutions/year_2024/mod.rs @@ -0,0 +1,11 @@ +use super::DayAssociations; + +pub mod day_01; + +pub fn solutions() -> DayAssociations { + let associations: Vec<(i32, super::BoxedSolution)> = vec![ + (1, Box::new(day_01::Day01 {})), + ]; + + associations.into_iter().collect() +} diff --git a/src/lib/utils/cli.rs b/src/lib/utils/cli.rs index 881456f..8e9cadd 100644 --- a/src/lib/utils/cli.rs +++ b/src/lib/utils/cli.rs @@ -17,14 +17,14 @@ impl CommandLineInterface { .version("v0.1") .arg( Arg::with_name(YEARS) - .default_value("2015-2022") + .default_value("2024") .help("Specify yearly solutions to execute") .long("year") .short("y") .takes_value(true) .use_delimiter(true) .validator(validate_int_sequence) - .value_name("[2015-2022]"), + .value_name("[2015-2024]"), ) .arg( Arg::with_name(DAYS)