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,34 +20,58 @@ 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() {
let mut dir = None; if safe_line(line) {
let mut last = None;
let mut lsafe = true;
for v in line.iter() {
if let Some(l) = last {
last = Some(v);
let d = v - l;
let s = Sign::new(d);
if let Some(p) = dir {
if p != s {
lsafe = false;
break;
}
}
dir = Some(s);
if d.abs() > 3 || d.abs() < 1 {
lsafe = false;
break;
}
} else {
last = Some(v);
}
}
if lsafe {
safe += 1; safe += 1;
} }
} }
safe
}
fn safe_line(line: &[i64]) -> bool {
let mut dir = None;
let mut last = None;
let mut lsafe = true;
for v in line.iter() {
if let Some(l) = last {
last = Some(v);
let d = v - l;
let s = Sign::new(d);
if let Some(p) = dir {
if p != s {
lsafe = false;
break;
}
}
dir = Some(s);
if d.abs() > 3 || d.abs() < 1 {
lsafe = false;
break;
}
} else {
last = Some(v);
}
}
lsafe
}
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);
}
} }