From 6015b6ec38903838ab1c678c60824712830c3e78 Mon Sep 17 00:00:00 2001 From: Malte Date: Mon, 2 Dec 2024 10:47:53 +0100 Subject: [PATCH] add day02 solution --- 2024/src/day02.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 2024/src/lib.rs | 1 + 2 files changed, 67 insertions(+) create mode 100644 2024/src/day02.rs diff --git a/2024/src/day02.rs b/2024/src/day02.rs new file mode 100644 index 0000000..cf45eb2 --- /dev/null +++ b/2024/src/day02.rs @@ -0,0 +1,66 @@ +use std::fs::read_to_string; + +fn check_report(report: &Vec) -> bool { + let desc = report[0] > report[1]; + for x in report.windows(2) { + let prev = if desc { x[0] } else { x[1] }; + let curr = if desc { x[1] } else { x[0] }; + let dist = prev - curr; + if dist > 3 || dist < 1 || prev < curr { + return false; + } + } + true +} + +pub fn stage1(input: &str) -> usize { + read_to_string(input) + .unwrap() + .lines() + .map(|line| { + line.split_whitespace() + .map(|x| x.parse::().unwrap()) + .collect::>() + }) + .filter(|report| check_report(report)) + .count() +} + +pub fn stage2(input: &str) -> usize { + read_to_string(input) + .unwrap() + .lines() + .map(|line| { + line.split_whitespace() + .map(|x| x.parse::().unwrap()) + .collect::>() + }) + .filter(|report| { + for y in 0..report.len() { + let mut variant = report.clone(); + variant.remove(y); + if check_report(&variant) { + return true; + } + } + false + }) + .count() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_stage1() { + assert_eq!(stage1("input/02_input.example"), 2); + assert_eq!(stage1("input/02_input.txt"), 463); + } + + #[test] + fn test_stage2() { + assert_eq!(stage2("input/02_input.example"), 4); + assert_eq!(stage2("input/02_input.txt"), 514); + } +} diff --git a/2024/src/lib.rs b/2024/src/lib.rs index c3ba043..bc52e1c 100644 --- a/2024/src/lib.rs +++ b/2024/src/lib.rs @@ -1,2 +1,3 @@ #[allow(dead_code)] mod day01; +mod day02;