Add Rust day 2

main
Bram 2024-12-03 11:39:10 +00:00
parent f6a860f283
commit 555e4aa024
7 changed files with 1082 additions and 0 deletions

1000
inputs/02.txt Normal file

File diff suppressed because it is too large Load Diff

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

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

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

@ -0,0 +1,26 @@
use crate::utils;
pub fn answer(text : &str) -> usize {
text.split("\n")
.map(parse_line)
.filter(is_safe_line)
.count()
}
fn is_safe_line(v : &Vec<i32>) -> bool {
let diff : Vec<i32> = v
.windows(2)
.filter_map(|v| Some(v.get(0)? - v.get(1)?))
.collect();
let all_increasing : bool = diff.iter().all(|&x| x < 0);
let all_decreasing : bool = diff.iter().all(|&x| x > 0);
let all_bounded_ok : bool = diff.iter().all(|&x| x.abs() <= 3);
all_bounded_ok && (all_increasing || all_decreasing)
}
fn parse_line(s : &str) -> Vec<i32> {
s.split(" ").filter_map(utils::str_to_i32).collect()
}

43
src/day_02/part_2.rs Normal file
View File

@ -0,0 +1,43 @@
use crate::utils;
pub fn answer(text : &str) -> usize {
text.split("\n")
.map(parse_line)
.filter(is_dampened_safe_line)
.count()
}
fn is_dampened_safe_line(v : &Vec<i32>) -> bool {
if is_safe_line(v) {
return true;
}
for i in 0..v.len() {
let mut cv = v.to_vec();
cv.remove(i);
if is_safe_line(&cv) {
return true;
}
}
false
}
fn is_safe_line(v : &Vec<i32>) -> bool {
let diff : Vec<i32> = v
.windows(2)
.filter_map(|v| Some(v.get(0)? - v.get(1)?))
.collect();
let all_increasing : bool = diff.iter().all(|&x| x < 0);
let all_decreasing : bool = diff.iter().all(|&x| x > 0);
let all_bounded_ok : bool = diff.iter().all(|&x| x.abs() <= 3);
all_bounded_ok && (all_increasing || all_decreasing)
}
fn parse_line(s : &str) -> Vec<i32> {
s.split(" ").filter_map(utils::str_to_i32).collect()
}

View File

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

View File

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

View File

@ -10,6 +10,10 @@ pub fn read_from_file(name : &str) -> String {
}
}
pub fn str_to_i32(s : &str) -> Option<i32> {
s.trim().to_string().parse::<i32>().ok()
}
pub fn str_to_u32(s : &str) -> Option<u32> {
s.trim().to_string().parse::<u32>().ok()
}