Add Rust day 1

main
Bram 2024-12-03 11:37:59 +00:00
parent e91a164178
commit f6a860f283
8 changed files with 1079 additions and 0 deletions

6
Cargo.toml Normal file
View File

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

1000
inputs/01.txt Normal file

File diff suppressed because it is too large Load Diff

2
src/day_01/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod part_1;
pub mod part_2;

26
src/day_01/part_1.rs Normal file
View File

@ -0,0 +1,26 @@
use crate::utils;
pub fn answer(lines : &str) -> u32 {
let ( mut left, mut right ) : ( Vec<u32>, Vec<u32> ) = lines
.split("\n")
.filter_map(parse_line)
.unzip();
left.sort_unstable();
right.sort_unstable();
left.iter()
.zip(right.iter())
.map(|(x, y)| abs_diff(&x, &y))
.sum()
}
fn abs_diff(l : &u32, r : &u32) -> u32 {
if l >= r { l - r } else { r - l }
}
fn parse_line(s : &str) -> Option<( u32, u32 )> {
let (left, right) = s.trim().split_once(" ")?;
Some(( utils::str_to_u32(left)?, utils::str_to_u32(right)? ))
}

18
src/day_01/part_2.rs Normal file
View File

@ -0,0 +1,18 @@
use crate::utils;
pub fn answer(s : &str) -> u32 {
let ( left, right ) : ( Vec<u32>, Vec<u32> ) = s
.split("\n")
.filter_map(parse_line)
.unzip();
left.iter()
.map(|x| right.iter().filter(|y| x == *y).count() as u32 * x)
.sum()
}
fn parse_line(s : &str) -> Option<( u32, u32 )> {
let (left, right) = s.trim().split_once(" ")?;
Some(( utils::str_to_u32(left)?, utils::str_to_u32(right)? ))
}

9
src/lib.rs Normal file
View File

@ -0,0 +1,9 @@
mod utils;
mod day_01;
pub fn day_01() {
let s : String = utils::read_from_file("inputs/01.txt");
println!("Day 01 part 1: {}", day_01::part_1::answer(s.as_str()));
println!("Day 01 part 2: {}", day_01::part_2::answer(s.as_str()));
}

3
src/main.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
aoc_2024::day_01();
}

15
src/utils/mod.rs Normal file
View File

@ -0,0 +1,15 @@
use std::fs;
pub fn read_from_file(name : &str) -> String {
match fs::read_to_string(name) {
Err(error) => {
println!("Failed to read file {name}: {error}");
String::new()
},
Ok(s) => s,
}
}
pub fn str_to_u32(s : &str) -> Option<u32> {
s.trim().to_string().parse::<u32>().ok()
}