day2, part 2

This commit is contained in:
Joe Ardent 2024-12-17 19:13:49 -08:00
parent f89520a125
commit 9b4ec1337e

View file

@ -1,6 +1,7 @@
fn main() { fn main() {
let input = std::fs::read_to_string("input").unwrap(); let input = std::fs::read_to_string("input").unwrap();
println!("{}", pt1(&input)); println!("{}", pt1(&input));
println!("{}", pt2(&input));
} }
#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[derive(Debug, PartialEq, Eq, Clone, Copy)]
@ -19,6 +20,14 @@ fn pt1(input: &str) -> usize {
let input = parse(input); let input = parse(input);
let mut safe = 0; let mut safe = 0;
for line in input.iter() { for line in input.iter() {
if safe_line(line) {
safe += 1;
}
}
safe
}
fn safe_line(line: &[i64]) -> bool {
let mut dir = None; let mut dir = None;
let mut last = None; let mut last = None;
let mut lsafe = true; let mut lsafe = true;
@ -42,11 +51,27 @@ fn pt1(input: &str) -> usize {
last = Some(v); last = Some(v);
} }
} }
if lsafe { lsafe
safe += 1;
}
} }
fn pt2(input: &str) -> usize {
let input = parse(input);
let mut safe = 0;
for line in input.iter() {
if safe_line(line) {
safe += 1;
} else {
for i in 0..(line.len()) {
let left = &line[0..i];
let right = &line[(i + 1)..(line.len())];
let line: Vec<i64> = left.iter().cloned().chain(right.iter().cloned()).collect();
if safe_line(&line) {
safe += 1;
break;
}
}
}
}
safe safe
} }
@ -59,6 +84,7 @@ fn parse(input: &str) -> Vec<Vec<i64>> {
lines lines
} }
#[cfg(test)]
mod test { mod test {
use super::*; use super::*;
@ -74,4 +100,10 @@ mod test {
let safe = pt1(INPUT); let safe = pt1(INPUT);
assert_eq!(2, safe); assert_eq!(2, safe);
} }
#[test]
fn tp2() {
let safe = pt2(INPUT);
assert_eq!(4, safe);
}
} }