This commit is contained in:
Rh4096 2024-12-03 18:32:40 +07:00
parent 876ca26900
commit 38b90ed1ff

View file

@ -1,12 +1,6 @@
use super::AocSolution; use super::AocSolution;
#[derive(Clone, Copy)] fn is_safe(levels: &[i32]) -> bool {
pub struct AocDayTwoSolution;
struct LevelValidator;
impl LevelValidator {
fn is_safe(&self, levels: &[i32]) -> bool {
let dec = levels[0] > levels[1]; let dec = levels[0] > levels[1];
for (cur, nxt) in levels.windows(2).map(|w| (w[0], w[1])) { for (cur, nxt) in levels.windows(2).map(|w| (w[0], w[1])) {
@ -20,27 +14,27 @@ impl LevelValidator {
true true
} }
fn is_safe_with_rem(&self, levels: &[i32]) -> bool { fn is_safe_with_rem(levels: &[i32]) -> bool {
for i in 0..levels.len() { for i in 0..levels.len() {
let mut lvl = levels[0..i].to_vec(); let mut lvl = levels[0..i].to_vec();
lvl.extend_from_slice(&levels[(i + 1)..]); lvl.extend_from_slice(&levels[(i + 1)..]);
if self.is_safe(&lvl) { if is_safe(&lvl) {
return true; return true;
} }
} }
false false
} }
}
#[derive(Clone, Copy)]
pub struct AocDayTwoSolution;
impl AocSolution for AocDayTwoSolution { impl AocSolution for AocDayTwoSolution {
type Output = u64; type Output = u64;
const INPUT: &str = include_str!("../../input/day2.txt"); const INPUT: &str = include_str!("../../input/day2.txt");
fn part_one(&self) -> Self::Output { fn part_one(&self) -> Self::Output {
let validator = LevelValidator;
Self::INPUT Self::INPUT
.lines() .lines()
.map(|n| { .map(|n| {
@ -48,13 +42,11 @@ impl AocSolution for AocDayTwoSolution {
.filter_map(|x| x.parse::<i32>().ok()) .filter_map(|x| x.parse::<i32>().ok())
.collect::<Vec<_>>() .collect::<Vec<_>>()
}) })
.filter(|s| validator.is_safe(s)) .filter(|s| is_safe(s))
.count() as u64 .count() as u64
} }
fn part_two(&self) -> Self::Output { fn part_two(&self) -> Self::Output {
let validator = LevelValidator;
Self::INPUT Self::INPUT
.lines() .lines()
.map(|n| { .map(|n| {
@ -62,7 +54,7 @@ impl AocSolution for AocDayTwoSolution {
.filter_map(|x| x.parse::<i32>().ok()) .filter_map(|x| x.parse::<i32>().ok())
.collect::<Vec<_>>() .collect::<Vec<_>>()
}) })
.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 .count() as u64
} }
} }