This commit is contained in:
Fabian Schmidt 2024-12-01 20:24:01 +01:00
parent 5531e8aa7a
commit a1183f8ef4
5 changed files with 1085 additions and 1 deletions

1000
y2024/resources/1_input.txt Normal file

File diff suppressed because it is too large Load Diff

20
y2024/src/bin/d1.rs Normal file
View File

@ -0,0 +1,20 @@
use std::fs;
use y2024::days::d1;
fn main() {
part1();
part2();
}
fn part1() {
let root = env!("CARGO_MANIFEST_DIR");
let content = fs::read_to_string(format!("{root}/resources/1_input.txt")).unwrap();
println!("{}", d1::process_part1(&content));
}
fn part2() {
let root = env!("CARGO_MANIFEST_DIR");
let content = fs::read_to_string(format!("{root}/resources/1_input.txt")).unwrap();
println!("{}", d1::process_part2(&content));
}

62
y2024/src/days/d1.rs Normal file
View File

@ -0,0 +1,62 @@
use std::{collections::HashMap, iter::zip};
pub fn process_part1(input: &str) -> i32 {
let mut left = Vec::new();
let mut right = Vec::new();
input.lines().for_each(|line| {
let (left_val, right_val) = line.split_once(" ").unwrap();
left.push(left_val.parse::<i32>().unwrap());
right.push(right_val.parse::<i32>().unwrap());
});
left.sort();
right.sort();
let mut res = 0;
for (left_val, right_val) in zip(left, right) {
res += (left_val - right_val).abs();
}
res
}
pub fn process_part2(input: &str) -> i32 {
let mut left = Vec::new();
let mut right = HashMap::new();
input.lines().for_each(|line| {
let (left_val, right_val) = line.split_once(" ").unwrap();
left.push(left_val.parse::<i32>().unwrap());
right
.entry(right_val.parse::<i32>().unwrap())
.and_modify(|value| *value += 1)
.or_insert(1);
});
left.sort();
let mut res = 0;
for left_val in left {
let right_val_count = right.get(&left_val).unwrap_or(&0);
res += left_val * right_val_count;
}
res
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &str = "3 4
4 3
2 5
1 3
3 9
3 3";
#[test]
fn part1() {
let result = process_part1(INPUT);
assert_eq!(result, 11);
}
#[test]
fn part2() {
let result = process_part2(INPUT);
assert_eq!(result, 31);
}
}

2
y2024/src/days/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod d1;

View File

@ -1 +1 @@
pub mod days;