This commit is contained in:
Aaron Manning 2024-12-06 18:18:34 +11:00
parent c2575cbcea
commit 7bf66496af
3 changed files with 78 additions and 0 deletions

7
day-02/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "day-02"
version = "0.1.0"

6
day-02/Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "day-02"
version = "0.1.0"
edition = "2021"
[dependencies]

65
day-02/src/main.rs Normal file
View File

@ -0,0 +1,65 @@
const INPUT: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/input.txt"));
fn main() {
let mut safe = 0;
for line in INPUT.lines() {
let report = line
.split_whitespace()
.filter_map(|num| {
str::parse::<u8>(num).ok()
});
safe += u16::from(is_safe(report));
}
println!("Part 1: {}", safe);
let mut still_safe = 0;
for line in INPUT.lines() {
let report = line
.split_whitespace()
.filter_map(|num| {
str::parse::<u8>(num).ok()
});
still_safe += u16::from(is_still_safe(report));
}
println!("Part 2: {}", still_safe);
}
fn is_safe(mut report: impl Iterator<Item = u8>) -> bool {
let mut ascending = true;
let mut descending = true;
let mut correct_gaps = true;
let Some(mut prev) = report.next() else {
return true;
};
while let Some(level) = report.next() {
ascending &= prev <= level;
descending &= prev >= level;
correct_gaps &= matches!(prev.abs_diff(level), 1..=3);
prev = level;
}
(ascending || descending) && correct_gaps
}
fn is_still_safe(report: impl Iterator<Item = u8>) -> bool {
let report = report.collect::<Vec<_>>();
let mut is_still_safe = false;
for removal in 0..report.len() {
let altered_report = report.iter().copied().enumerate().filter_map(|(idx, level)| {
if idx == removal {
None
} else {
Some(level)
}
});
is_still_safe |= is_safe(altered_report);
};
is_still_safe
}