From 7093b44099ad432ee5f613123b37152a4430fa83 Mon Sep 17 00:00:00 2001 From: Ben C Date: Sun, 1 Dec 2024 01:04:26 -0500 Subject: [PATCH] 2024 Day 1 - Organize --- utils/src/lib.rs | 4 ++++ utils/src/misc.rs | 12 ++++++++++++ years/2024/src/day_1.rs | 35 ++++++++++++++++++++++------------- 3 files changed, 38 insertions(+), 13 deletions(-) create mode 100644 utils/src/misc.rs diff --git a/utils/src/lib.rs b/utils/src/lib.rs index 4d32b6f..c201c42 100644 --- a/utils/src/lib.rs +++ b/utils/src/lib.rs @@ -3,9 +3,12 @@ pub mod dir; pub mod geom; pub mod grid; pub mod line; +pub mod misc; pub mod pos; pub mod range; +#[allow(unused)] + pub mod prelude { pub use crate::dir::*; pub use crate::geom; @@ -13,6 +16,7 @@ pub mod prelude { pub use crate::grid::tiles::*; pub use crate::grid::*; pub use crate::line::*; + pub use crate::misc::*; pub use crate::pos::*; pub use crate::range::*; } diff --git a/utils/src/misc.rs b/utils/src/misc.rs new file mode 100644 index 0000000..d9ec7f4 --- /dev/null +++ b/utils/src/misc.rs @@ -0,0 +1,12 @@ +use std::{collections::HashMap, hash::Hash}; + +pub fn counts(l: impl Iterator) -> HashMap { + let (min, max) = l.size_hint(); + l.fold( + HashMap::with_capacity(max.unwrap_or(min)), + |mut agg, curr| { + agg.entry(curr).and_modify(|x| *x += 1).or_insert(1); + agg + }, + ) +} diff --git a/years/2024/src/day_1.rs b/years/2024/src/day_1.rs index a77b0ae..ee2e599 100644 --- a/years/2024/src/day_1.rs +++ b/years/2024/src/day_1.rs @@ -1,7 +1,5 @@ - -use std::collections::HashMap; - use advent_core::{Day, day_stuff, ex_for_day}; +use utils::misc::counts; pub struct Day1; @@ -13,23 +11,34 @@ impl Day for Day1 { let (mut l, mut r) = input; l.sort_unstable(); r.sort_unstable(); - Some(l.into_iter().zip(r.into_iter()).map(|(l, r)| (l - r).abs()).sum::().to_string()) + + Some(l.into_iter() + .zip(r.into_iter()) + .map(|(l, r)| (l - r).abs()) + .sum::() + .to_string() + ) } fn part_2(input: Self::Input) -> Option { let (l, r) = input; - let apr = r.into_iter().fold(HashMap::new(), |mut a, curr| { - a.entry(curr).and_modify(|x| { *x += 1 }).or_insert(1); - a - }); - Some(l.into_iter().map(|l| l * apr.get(&l).unwrap_or(&0)).sum::().to_string()) + let apr = counts(r.into_iter()); + Some(l.into_iter() + .map(|l| + l as u64 * apr.get(&l).unwrap_or(&0) + ) + .sum::() + .to_string() + ) } fn parse_input(input: &str) -> Self::Input { - input.split("\n").map(|l| { - let mut l = l.trim().split_ascii_whitespace(); - (l.next().map(|x| x.parse::().unwrap()).unwrap(), l.next().map(|x| x.parse::().unwrap()).unwrap()) - }).collect::<(Vec<_>, Vec<_>)>() + input.split("\n").map(|line| { + let mut split = line.trim().split_ascii_whitespace(); + let left = split.next().unwrap().parse::().unwrap(); + let right = split.next().unwrap().parse::().unwrap(); + (left, right) + }).collect() } } -- 2.51.2