From 51e34a6b066a119406b68061a0f98d158e6b45b8 Mon Sep 17 00:00:00 2001 From: Musselman Date: Wed, 4 Dec 2024 01:01:20 -0600 Subject: [PATCH] Upload day 1 --- README.md | 8 +++++ data/examples/01.txt | 0 src/bin/01.rs | 85 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+) create mode 100644 data/examples/01.txt create mode 100644 src/bin/01.rs diff --git a/README.md b/README.md index a155efa..da2628d 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,14 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www. + +## Benchmarks + +| Day | Part 1 | Part 2 | +| :---: | :---: | :---: | +| [Day 1](./src/bin/01.rs) | `89.5µs` | `125.4µs` | + +**Total: 0.21ms** --- diff --git a/data/examples/01.txt b/data/examples/01.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/bin/01.rs b/src/bin/01.rs new file mode 100644 index 0000000..cdc6af4 --- /dev/null +++ b/src/bin/01.rs @@ -0,0 +1,85 @@ +advent_of_code::solution!(1); +use std::collections::HashMap; + +pub fn part_one(input: &str) -> Option { + if input.is_empty() { + return None; + } + + let mut left: Vec = Vec::new(); + let mut right: Vec = Vec::new(); + + for line in input.lines() { + let mut split = line.split_whitespace(); + + if let (Some(l), Some(r)) = (split.next(), split.next()) { + if let (Ok(l_number), Ok(r_number)) = (l.parse::(), r.parse::()) { + left.push(l_number); + right.push(r_number); + } + } + } + + left.sort(); + right.sort(); + + let total_distance: u32 = left + .iter() + .zip(right.iter()) + .map(|(&x, &y)| if x > y { x - y } else { y - x }) + .sum(); + + Some(total_distance) +} + +pub fn part_two(input: &str) -> Option { + if input.is_empty() { + return None; + } + + let mut left: Vec = Vec::new(); + let mut right: Vec = Vec::new(); + + for line in input.lines() { + let mut split = line.split_whitespace(); + + if let (Some(l), Some(r)) = (split.next(), split.next()) { + if let (Ok(l_number), Ok(r_number)) = (l.parse::(), r.parse::()) { + left.push(l_number); + right.push(r_number); + } + } + } + + left.sort(); + right.sort(); + + let mut right_list_counts: HashMap = HashMap::new(); + for &num in &right { + *right_list_counts.entry(num).or_insert(0) += 1; + } + + let total_similarity_score: u32 = left + .iter() + .map(|&num| num * right_list_counts.get(&num).unwrap_or(&0)) + .sum(); + + Some(total_similarity_score) +} + +#[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, None); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, None); + } +}