From 38b90ed1ffeaf71da1dc4bc1549adc019b583060 Mon Sep 17 00:00:00 2001 From: Rh4096 Date: Tue, 3 Dec 2024 18:32:40 +0700 Subject: [PATCH] day 2.11 --- src/solutions/day_2.rs | 66 +++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 37 deletions(-) diff --git a/src/solutions/day_2.rs b/src/solutions/day_2.rs index 2a89435..1c0cb56 100644 --- a/src/solutions/day_2.rs +++ b/src/solutions/day_2.rs @@ -1,46 +1,40 @@ use super::AocSolution; +fn is_safe(levels: &[i32]) -> bool { + let dec = levels[0] > levels[1]; + + for (cur, nxt) in levels.windows(2).map(|w| (w[0], w[1])) { + let diff = cur - nxt; + + if diff == 0 || diff.abs() > 3 || (diff > 0) != dec { + return false; + } + } + + true +} + +fn is_safe_with_rem(levels: &[i32]) -> bool { + for i in 0..levels.len() { + let mut lvl = levels[0..i].to_vec(); + lvl.extend_from_slice(&levels[(i + 1)..]); + + if is_safe(&lvl) { + return true; + } + } + + false +} + #[derive(Clone, Copy)] pub struct AocDayTwoSolution; -struct LevelValidator; - -impl LevelValidator { - fn is_safe(&self, levels: &[i32]) -> bool { - let dec = levels[0] > levels[1]; - - for (cur, nxt) in levels.windows(2).map(|w| (w[0], w[1])) { - let diff = cur - nxt; - - if diff == 0 || diff.abs() > 3 || (diff > 0) != dec { - return false; - } - } - - true - } - - fn is_safe_with_rem(&self, levels: &[i32]) -> bool { - for i in 0..levels.len() { - let mut lvl = levels[0..i].to_vec(); - lvl.extend_from_slice(&levels[(i + 1)..]); - - if self.is_safe(&lvl) { - return true; - } - } - - false - } -} - impl AocSolution for AocDayTwoSolution { type Output = u64; const INPUT: &str = include_str!("../../input/day2.txt"); fn part_one(&self) -> Self::Output { - let validator = LevelValidator; - Self::INPUT .lines() .map(|n| { @@ -48,13 +42,11 @@ impl AocSolution for AocDayTwoSolution { .filter_map(|x| x.parse::().ok()) .collect::>() }) - .filter(|s| validator.is_safe(s)) + .filter(|s| is_safe(s)) .count() as u64 } fn part_two(&self) -> Self::Output { - let validator = LevelValidator; - Self::INPUT .lines() .map(|n| { @@ -62,7 +54,7 @@ impl AocSolution for AocDayTwoSolution { .filter_map(|x| x.parse::().ok()) .collect::>() }) - .filter(|s| validator.is_safe(s) || validator.is_safe_with_rem(s)) + .filter(|s| is_safe(s) || is_safe_with_rem(s)) .count() as u64 } }