day 2
This commit is contained in:
parent
c2575cbcea
commit
7bf66496af
7
day-02/Cargo.lock
generated
Normal file
7
day-02/Cargo.lock
generated
Normal 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
6
day-02/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "day-02"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
65
day-02/src/main.rs
Normal file
65
day-02/src/main.rs
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user