A new advent of code, day 1 finished

This commit is contained in:
2024-12-01 22:44:52 +01:00
parent fb41ac47f1
commit 0dc8d476a6
4 changed files with 1106 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
[package]
name = "main"
version = "0.1.0"
edition = "2021"
[dependencies]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,94 @@
use std::{collections::HashMap, iter::zip};
fn distance<A>(a: A, b: A) -> A
where
A: std::ops::Sub<Output = A> + Ord,
{
if a < b {
return b.sub(a);
} else {
return a.sub(b);
}
}
fn solve_1(input: &str) -> u32 {
let input: Vec<Vec<u32>> = input
.lines()
.map(|element| {
element
.split_ascii_whitespace()
.map(|numbers| numbers.parse::<u32>().unwrap())
.collect()
})
.collect();
// Double collect(), wowsers that's ugly but it works?
let mut left: Vec<u32> = input.iter().map(|v| v[0].to_owned()).collect();
let mut right: Vec<u32> = input.iter().map(|v| v[1].to_owned()).collect();
left.sort();
right.sort();
return zip(left, right).fold(0, |x, (l, r)| x + distance(l, r));
}
fn solve_2(input: &str) -> u32 {
let input: Vec<Vec<u32>> = input
.lines()
.map(|element| {
element
.split_ascii_whitespace()
.map(|numbers| numbers.parse::<u32>().unwrap())
.collect()
})
.collect();
let left: Vec<u32> = input.iter().map(|v| v[0].to_owned()).collect();
let right: Vec<u32> = input.iter().map(|v| v[1].to_owned()).collect();
let mut occurrences: HashMap<u32, u32> = HashMap::new();
for r in right.into_iter() {
occurrences.insert(
r,
match occurrences.get(&r) {
None => 1,
Some(v) => v + 1,
},
);
}
return left
.into_iter()
.fold(0, |s, l| s + l * occurrences.get(&l).unwrap_or(&0));
}
fn main() {
println!("Hello, this is Patrick!");
let input_text = include_str!("../input.txt");
let result_1 = solve_1(input_text);
println!("The total distance between the two lists is {}", result_1);
let result_2 = solve_2(input_text);
println!("The similarity score of the two lists is {}", result_2);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
let test_input = include_str!("../test.txt");
assert_eq!(solve_1(test_input), 11);
}
#[test]
fn test_2() {
let test_input = include_str!("../test.txt");
assert_eq!(solve_2(test_input), 31);
}
}

View File

@@ -0,0 +1,6 @@
3 4
4 3
2 5
1 3
3 9
3 3