commit 04bbb3a559754ab4294956291827ba8e2bceefae Author: CrispyPin Date: Thu Dec 5 13:46:45 2024 +0100 day 1 part 1 in rust diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8bc339b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +target +*.out +Cargo.lock +input.txt diff --git a/day_01/Cargo.toml b/day_01/Cargo.toml new file mode 100644 index 0000000..d600bcb --- /dev/null +++ b/day_01/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day_01" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/day_01/src/main.rs b/day_01/src/main.rs new file mode 100644 index 0000000..536c6a6 --- /dev/null +++ b/day_01/src/main.rs @@ -0,0 +1,36 @@ +fn main() { + let input = include_str!("../input.txt"); + let mut left: Vec = Vec::new(); + let mut right: Vec = Vec::new(); + let count = input.lines().count(); + for line in input.lines() { + let (l, r) = line.split_once(" ").unwrap(); + left.push(l.parse().unwrap()); + right.push(r.parse().unwrap()); + } + let mut sum: u32 = 0; + for _ in 0..count { + let (il, minl) = smallest(&left); + let (ir, minr) = smallest(&right); + sum += if minl > minr { + minl - minr + } else { + minr - minl + }; + left.swap_remove(il); + right.swap_remove(ir); + } + println!("{sum}"); +} + +fn smallest(source: &[u32]) -> (usize, u32) { + let mut min = 99999; + let mut min_index = 0; + for (i, &n) in source.iter().enumerate() { + if n < min { + min = n; + min_index = i; + } + } + (min_index, min) +}