Advent of Code solutions

2024 Day 1 - Organize

bwc9876.dev 7093b440 35b43512

verified
+38 -13
+4
utils/src/lib.rs
··· 3 3 pub mod geom; 4 4 pub mod grid; 5 5 pub mod line; 6 + pub mod misc; 6 7 pub mod pos; 7 8 pub mod range; 9 + 10 + #[allow(unused)] 8 11 9 12 pub mod prelude { 10 13 pub use crate::dir::*; ··· 13 16 pub use crate::grid::tiles::*; 14 17 pub use crate::grid::*; 15 18 pub use crate::line::*; 19 + pub use crate::misc::*; 16 20 pub use crate::pos::*; 17 21 pub use crate::range::*; 18 22 }
+12
utils/src/misc.rs
··· 1 + use std::{collections::HashMap, hash::Hash}; 2 + 3 + pub fn counts<T: Hash + Eq + PartialEq>(l: impl Iterator<Item = T>) -> HashMap<T, u64> { 4 + let (min, max) = l.size_hint(); 5 + l.fold( 6 + HashMap::with_capacity(max.unwrap_or(min)), 7 + |mut agg, curr| { 8 + agg.entry(curr).and_modify(|x| *x += 1).or_insert(1); 9 + agg 10 + }, 11 + ) 12 + }
+22 -13
years/2024/src/day_1.rs
··· 1 - 2 - use std::collections::HashMap; 3 - 4 1 use advent_core::{Day, day_stuff, ex_for_day}; 2 + use utils::misc::counts; 5 3 6 4 pub struct Day1; 7 5 ··· 13 11 let (mut l, mut r) = input; 14 12 l.sort_unstable(); 15 13 r.sort_unstable(); 16 - Some(l.into_iter().zip(r.into_iter()).map(|(l, r)| (l - r).abs()).sum::<i32>().to_string()) 14 + 15 + Some(l.into_iter() 16 + .zip(r.into_iter()) 17 + .map(|(l, r)| (l - r).abs()) 18 + .sum::<i32>() 19 + .to_string() 20 + ) 17 21 } 18 22 19 23 fn part_2(input: Self::Input) -> Option<String> { 20 24 let (l, r) = input; 21 - let apr = r.into_iter().fold(HashMap::new(), |mut a, curr| { 22 - a.entry(curr).and_modify(|x| { *x += 1 }).or_insert(1); 23 - a 24 - }); 25 - Some(l.into_iter().map(|l| l * apr.get(&l).unwrap_or(&0)).sum::<i32>().to_string()) 25 + let apr = counts(r.into_iter()); 26 + Some(l.into_iter() 27 + .map(|l| 28 + l as u64 * apr.get(&l).unwrap_or(&0) 29 + ) 30 + .sum::<u64>() 31 + .to_string() 32 + ) 26 33 } 27 34 28 35 fn parse_input(input: &str) -> Self::Input { 29 - input.split("\n").map(|l| { 30 - let mut l = l.trim().split_ascii_whitespace(); 31 - (l.next().map(|x| x.parse::<i32>().unwrap()).unwrap(), l.next().map(|x| x.parse::<i32>().unwrap()).unwrap()) 32 - }).collect::<(Vec<_>, Vec<_>)>() 36 + input.split("\n").map(|line| { 37 + let mut split = line.trim().split_ascii_whitespace(); 38 + let left = split.next().unwrap().parse::<i32>().unwrap(); 39 + let right = split.next().unwrap().parse::<i32>().unwrap(); 40 + (left, right) 41 + }).collect() 33 42 } 34 43 35 44 }