aoc/year2024/
day01.rs

1//! # Historian Hysteria
2//!
3//! For part 2, the time needed to allocate memory and grow the map is a large percentage
4//! of the total. Creating the [`FastMap`] with capacity 1000 reduces this.
5use crate::util::hash::*;
6use crate::util::iter::*;
7use crate::util::parse::*;
8
9type Input = (Vec<u32>, Vec<u32>);
10
11pub fn parse(input: &str) -> Input {
12    input.iter_unsigned::<u32>().chunk::<2>().map(|[l, r]| (l, r)).unzip()
13}
14
15pub fn part1(input: &Input) -> u32 {
16    let (mut left, mut right) = input.clone();
17
18    left.sort_unstable();
19    right.sort_unstable();
20
21    left.iter().zip(right).map(|(l, r)| l.abs_diff(r)).sum()
22}
23
24pub fn part2(input: &Input) -> u32 {
25    let (left, right) = input;
26
27    let mut freq = FastMap::with_capacity(1_000);
28    right.iter().for_each(|r| *freq.entry(r).or_insert(0) += 1);
29
30    left.iter().filter_map(|l| freq.get(l).map(|f| l * f)).sum()
31}