Add Rust day 1
parent
e91a164178
commit
f6a860f283
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "aoc-2024"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,2 @@
|
|||
pub mod part_1;
|
||||
pub mod part_2;
|
|
@ -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)? ))
|
||||
}
|
|
@ -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)? ))
|
||||
}
|
|
@ -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()));
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
aoc_2024::day_01();
|
||||
}
|
|
@ -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()
|
||||
}
|
Loading…
Reference in New Issue