Day 1 on Day (almost) 3, sorry I'm late
This commit is contained in:
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/target
|
||||
7
Cargo.lock
generated
Normal file
7
Cargo.lock
generated
Normal file
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "advent-of-code-2024"
|
||||
version = "0.1.0"
|
||||
6
Cargo.toml
Normal file
6
Cargo.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "advent-of-code-2024"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
1000
assets/day_1_input
Normal file
1000
assets/day_1_input
Normal file
File diff suppressed because it is too large
Load Diff
5
src/advent_of_code/mod.rs
Normal file
5
src/advent_of_code/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
mod sun_01;
|
||||
|
||||
pub fn today() {
|
||||
let key = sun_01::sun_01("./assets/day_1_input").unwrap();
|
||||
}
|
||||
42
src/advent_of_code/sun_01.rs
Normal file
42
src/advent_of_code/sun_01.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use std::{fs::read_to_string, ops::Sub};
|
||||
|
||||
type Number = i32;
|
||||
type Key = i32;
|
||||
|
||||
pub fn sun_01(input: &str) -> Result<Key, ()> {
|
||||
let mut list_1: Vec<Number> = vec![];
|
||||
let mut list_2: Vec<Number> = vec![];
|
||||
let mut key: Number = 0;
|
||||
|
||||
for line in read_to_string(input).unwrap().lines() {
|
||||
if let Some((one, two)) = line.split_once(" ") {
|
||||
list_1.push(one.parse::<Number>().unwrap());
|
||||
list_2.push(two.parse::<Number>().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
if list_1.len() != list_2.len() {
|
||||
return Err(());
|
||||
}
|
||||
|
||||
// 1. Pair up the numbers by size and compare the distance between them: Sorting
|
||||
list_1.sort();
|
||||
list_2.sort();
|
||||
|
||||
// 2. Calc the distance between the pair elements
|
||||
for index in 0..list_1.len() {
|
||||
key += calc_distance(list_1[index], list_2[index]);
|
||||
}
|
||||
|
||||
Ok(Key)
|
||||
}
|
||||
|
||||
fn calc_distance<T>(num_1: T, num_2: T) -> T
|
||||
where
|
||||
T: PartialOrd + Sub<Output = T>,
|
||||
{
|
||||
if num_1 > num_2 {
|
||||
return num_1 - num_2;
|
||||
}
|
||||
return num_2 - num_1;
|
||||
}
|
||||
6
src/main.rs
Normal file
6
src/main.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
mod advent_of_code;
|
||||
|
||||
fn main() {
|
||||
advent_of_code::today();
|
||||
println!("Happy new year!");
|
||||
}
|
||||
Reference in New Issue
Block a user