day 1: part 1: rust
This commit is contained in:
parent
1a8565b67c
commit
d348f1ad22
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "part1"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,48 @@
|
|||
|
||||
fn vec_minimum(vec: &Vec<u64>) -> (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<u64>, nums2: Vec<u64>) -> 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<u64> = Vec::new();
|
||||
let mut nums2: Vec<u64> = 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(())
|
||||
}
|
Loading…
Reference in New Issue