diff --git a/data/examples/01.txt b/data/examples/01.txt new file mode 100644 index 0000000..dfca0b1 --- /dev/null +++ b/data/examples/01.txt @@ -0,0 +1,6 @@ +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 \ No newline at end of file diff --git a/src/bin/01.rs b/src/bin/01.rs new file mode 100644 index 0000000..6e946fa --- /dev/null +++ b/src/bin/01.rs @@ -0,0 +1,63 @@ +use std::collections::HashMap; + +advent_of_code::solution!(1); + +pub fn part_one(input: &str) -> Option { + let (mut l, mut r): (Vec, Vec) = input + .lines() + .map(|l| { + let mut nums = l.split_whitespace().map(|n| n.parse::().unwrap()); + (nums.next().unwrap(), nums.next().unwrap()) + }) + .unzip(); + + l.sort(); + r.sort(); + + let sum: i32 = l.iter().zip(r.iter()).map(|(l, r)| (l - r).abs()).sum(); + Some(sum as u32) +} + +pub fn part_two(input: &str) -> Option { + let (l, r): (Vec, Vec) = input + .lines() + .map(|l| { + let mut nums = l.split_whitespace().map(|n| n.parse::().unwrap()); + (nums.next().unwrap(), nums.next().unwrap()) + }) + .unzip(); + + let mut r_count: HashMap = HashMap::new(); + + for n in r.iter() { + *r_count.entry(*n).or_insert(0) += 1; + } + + let score: i32 = l + .iter() + .map(|&n| { + let count = *r_count.get(&n).unwrap_or(&0); + let score = n * count as i32; + score + }) + .sum(); + + Some(score as u32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(11)); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(31)); + } +}