day 1 part 1 in rust
This commit is contained in:
commit
04bbb3a559
3 changed files with 46 additions and 0 deletions
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
target
|
||||||
|
*.out
|
||||||
|
Cargo.lock
|
||||||
|
input.txt
|
6
day_01/Cargo.toml
Normal file
6
day_01/Cargo.toml
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
[package]
|
||||||
|
name = "day_01"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
36
day_01/src/main.rs
Normal file
36
day_01/src/main.rs
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
fn main() {
|
||||||
|
let input = include_str!("../input.txt");
|
||||||
|
let mut left: Vec<u32> = Vec::new();
|
||||||
|
let mut right: Vec<u32> = 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)
|
||||||
|
}
|
Loading…
Reference in a new issue