diff --git a/day02/src/main.rs b/day02/src/main.rs index 1c10151..548f279 100644 --- a/day02/src/main.rs +++ b/day02/src/main.rs @@ -1,6 +1,7 @@ fn main() { let input = std::fs::read_to_string("input").unwrap(); println!("{}", pt1(&input)); + println!("{}", pt2(&input)); } #[derive(Debug, PartialEq, Eq, Clone, Copy)] @@ -19,34 +20,58 @@ fn pt1(input: &str) -> usize { let input = parse(input); let mut safe = 0; for line in input.iter() { - 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); - } - } - if lsafe { + if safe_line(line) { 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 = left.iter().cloned().chain(right.iter().cloned()).collect(); + if safe_line(&line) { + safe += 1; + break; + } + } + } + } safe } @@ -59,6 +84,7 @@ fn parse(input: &str) -> Vec> { lines } +#[cfg(test)] mod test { use super::*; @@ -74,4 +100,10 @@ mod test { let safe = pt1(INPUT); assert_eq!(2, safe); } + + #[test] + fn tp2() { + let safe = pt2(INPUT); + assert_eq!(4, safe); + } }