From 92225c05db65dd6986340a9325c0e3540480cda4 Mon Sep 17 00:00:00 2001 From: Eric Fistons Date: Thu, 12 Jun 2025 22:34:50 +0200 Subject: [PATCH] Fix challenge --- src/main.rs | 56 +++++++++++++++-------------------------------------- 1 file changed, 16 insertions(+), 40 deletions(-) diff --git a/src/main.rs b/src/main.rs index 27bc2d2..f9be344 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,44 +1,20 @@ -#[derive(PartialEq, Debug)] -enum Order { - Up, - Down, - Stable, - Uninit, -} - +#[allow(dead_code)] fn find_peaks_and_valleys(values: &[isize]) -> Vec { - let mut peaks_and_valleys = vec![]; - let mut order = Order::Uninit; - for i in 1..values.len() { - let previous = values[i - 1]; - let current = values[i]; - - let new_order = match current - previous { - 0 => Order::Stable, - x if x > 0 => Order::Up, - x if x < 0 => Order::Down, - _ => unreachable!(), - }; - - println!( - "Compared {previous} ({}) and {current} ({}). Current order is {order:?}, new order is {new_order:?}", - i - 1, - i - ); - - if order != new_order && order != Order::Uninit { - peaks_and_valleys.push(i); - println!("Order changed, pushing {}", i) - } - order = new_order; - } - - peaks_and_valleys + values + .windows(3) + .enumerate() + .flat_map(|(idx, arr)| { + let (a, b, c) = (arr[0], arr[1], arr[2]); + if (b > a && b > c) || (b < a && b < c) { + Some(idx + 1) + } else { + None + } + }) + .collect() } -fn main() { - println!("{:?}", find_peaks_and_valleys(&[1, 2, 3, 4, 1, 8])); -} +fn main() {} #[cfg(test)] mod tests { @@ -47,7 +23,7 @@ mod tests { #[test] pub fn test() { assert_eq!( - find_peaks_and_valleys(&[1, 2, 1, 3, 4, 5, 4, 5, 2, 1, 2, 3]), + find_peaks_and_valleys(&[1, 2, 1, 3, 4, 5, 4, 3, 2, 1, 2, 3]), vec![1, 2, 5, 9] ); } @@ -61,7 +37,7 @@ mod tests { pub fn test_up_and_down() { assert_eq!( find_peaks_and_valleys(&[1, 0, 1, 0, 1, 0]), - vec![1, 2, 3, 4, 5] + vec![1, 2, 3, 4] ); }