|
| 1 | +use std::{collections::HashMap, i32, u32}; |
| 2 | + |
| 3 | +advent_of_code::solution!(1); |
| 4 | + |
| 5 | +fn parse(input: &str) -> (Vec<i32>, Vec<i32>) { |
| 6 | + input |
| 7 | + .lines() |
| 8 | + .map(|line| { |
| 9 | + let mut nums = line |
| 10 | + .split_whitespace() |
| 11 | + .map(|s| s.parse::<i32>().expect("A valid parse")); |
| 12 | + let left = nums.next().expect("A value on the left column"); |
| 13 | + let right = nums.next().expect("A value on the right column"); |
| 14 | + (left, right) |
| 15 | + }) |
| 16 | + .collect::<Vec<_>>() // Propagate the error if any |
| 17 | + .into_iter() |
| 18 | + .unzip() |
| 19 | +} |
| 20 | + |
| 21 | +pub fn part_one(input: &str) -> Option<u32> { |
| 22 | + let (mut col1, mut col2) = parse(&input); |
| 23 | + col1.sort_unstable(); |
| 24 | + col2.sort_unstable(); |
| 25 | + Some( |
| 26 | + col1.into_iter() |
| 27 | + .zip(col2.into_iter()) |
| 28 | + .map(|(a, b)| (a - b).abs() as u32) |
| 29 | + .sum::<u32>(), |
| 30 | + ) |
| 31 | +} |
| 32 | + |
| 33 | +pub fn part_two(input: &str) -> Option<u32> { |
| 34 | + let (col1, col2) = parse(&input); |
| 35 | + let mut counts = HashMap::new(); |
| 36 | + for num in col2 { |
| 37 | + counts.entry(num).and_modify(|c| *c += 1).or_insert(1); |
| 38 | + } |
| 39 | + Some(col1.into_iter().fold(0, |acc, x| { |
| 40 | + if let Some(&right_count) = counts.get(&x) { |
| 41 | + acc + (x * right_count) as u32 |
| 42 | + } else { |
| 43 | + acc |
| 44 | + } |
| 45 | + })) |
| 46 | +} |
| 47 | + |
| 48 | +#[cfg(test)] |
| 49 | +mod tests { |
| 50 | + use super::*; |
| 51 | + |
| 52 | + #[test] |
| 53 | + fn test_part_one() { |
| 54 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 55 | + assert_eq!(result, Some(11)); |
| 56 | + } |
| 57 | + |
| 58 | + #[test] |
| 59 | + fn test_part_two() { |
| 60 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 61 | + assert_eq!(result, Some(31)); |
| 62 | + } |
| 63 | +} |
0 commit comments