mirror of
https://github.com/Rhelvetican/aoc2024.git
synced 2024-12-23 06:51:40 +00:00
day 2.11
This commit is contained in:
parent
876ca26900
commit
38b90ed1ff
1 changed files with 29 additions and 37 deletions
|
@ -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::<i32>().ok())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.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::<i32>().ok())
|
||||
.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
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue