From e7cc1df936d5f8c83ce99114eec6927a2ea96e27 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Mon, 2 Dec 2024 12:19:04 -0600 Subject: [PATCH] WIP --- 2024/rust/src/day2.rs | 63 ++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 37 deletions(-) diff --git a/2024/rust/src/day2.rs b/2024/rust/src/day2.rs index 1ce19e3..f4342ea 100644 --- a/2024/rust/src/day2.rs +++ b/2024/rust/src/day2.rs @@ -24,55 +24,44 @@ impl FromStr for Report { impl Report { fn is_safe(&self, skip_index: Option) -> bool { - let mut ordering: Option = None; - let skip_index = skip_index.unwrap_or(self.levels.len() + 1); - let max = if skip_index < self.levels.len() { - self.levels.len() - 2 + let mut index_sequence: Box> = if let Some(i) = skip_index { + Box::new( + self.levels[0..i] + .iter() + .chain(self.levels[i + 1..self.levels.len()].iter()) + .into_iter(), + ) } else { - self.levels.len() - 1 + Box::new(self.levels.iter()) }; - - for i in 0..max { - let mut ai = i; - let mut bi = ai + 1; - if ai >= skip_index { - ai += 1 - }; - if bi >= skip_index { - bi += 1 - }; - let (a, b) = (self.levels[ai], self.levels[bi]); - if !Self::safe_level_pair(a, b, &ordering) { + let a = index_sequence.next().unwrap(); + let b = index_sequence.next().unwrap(); + let ordering = a.cmp(b); + if ordering == Ordering::Equal { + return false; + } + if !Self::safe_level_pair(*a, *b, ordering) { + return false; + } + println!("{a} {b} {ordering:?} {skip_index:?}"); + while let (a, Some(b)) = (b, index_sequence.next()) { + println!("{a} {b} {ordering:?}"); + if !Self::safe_level_pair(*a, *b, ordering) { return false; } - if ordering == None { - ordering = Some(a.cmp(&b)) - } } return true; } fn is_safe_with_any_single_level_removed(&self) -> bool { - for i in 0..self.levels.len() { - if self.is_safe(Some(i)) { - return true; - } - } - return false; + (0..self.levels.len()) + .into_iter() + .any(|i| self.is_safe(Some(i))) } - fn safe_level_pair(a: i64, b: i64, kind: &Option) -> bool { - if a == b { - return false; - } - if (a - b).abs() > 3 { - return false; - } - if kind.map(|o| o == a.cmp(&b)) == Some(false) { - return false; - } - return true; + fn safe_level_pair(a: i64, b: i64, kind: Ordering) -> bool { + kind == a.cmp(&b) && (a - b).abs() <= 3 } }