From d348f1ad22500675123c058759fdb2ac7142e34f Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Sun, 1 Dec 2024 10:27:50 +0100 Subject: [PATCH] day 1: part 1: rust --- 2024/days/01/part1/Cargo.toml | 6 +++++ 2024/days/01/part1/src/main.rs | 48 ++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 2024/days/01/part1/Cargo.toml create mode 100644 2024/days/01/part1/src/main.rs diff --git a/2024/days/01/part1/Cargo.toml b/2024/days/01/part1/Cargo.toml new file mode 100644 index 0000000..d85b608 --- /dev/null +++ b/2024/days/01/part1/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "part1" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/days/01/part1/src/main.rs b/2024/days/01/part1/src/main.rs new file mode 100644 index 0000000..e5204af --- /dev/null +++ b/2024/days/01/part1/src/main.rs @@ -0,0 +1,48 @@ + +fn vec_minimum(vec: &Vec) -> (usize, u64) { + let mut m: u64 = u64::MAX; + let mut index: usize = 0; + for (i, value) in vec.iter().enumerate() { + if *value < m { + m = *value; + index = i; + } + } + (index, m) +} + +fn vec_distance(nums1: Vec, nums2: Vec) -> u64 { + let mut nums1 = nums1.clone(); + let mut nums2 = nums2.clone(); + let mut distance: u64 = 0; + while nums1.len() > 0 { + let (idx1, min1) = vec_minimum(&nums1); + let (idx2, min2) = vec_minimum(&nums2); + let d = (min1 as i64 - min2 as i64).abs() as u64; + distance += d; + nums1.remove(idx1); + nums2.remove(idx2); + } + distance +} + +fn main() -> std::io::Result<()> { + let mut nums1: Vec = Vec::new(); + let mut nums2: Vec = Vec::new(); + for line in std::io::stdin().lines() { + let line = line.unwrap(); + if line == "" { + continue; + } + let mut parts = line.split(" "); + let num1 = parts.next().unwrap(); + let num1: u64 = num1.parse().unwrap(); + let num2 = parts.next().unwrap(); + let num2: u64 = num2.parse().unwrap(); + nums1.push(num1); + nums2.push(num2); + } + let distance = vec_distance(nums1, nums2); + println!("{}", distance); + Ok(()) +}