Improvments
parent
9559831318
commit
3446524d70
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "peak-and-valley"
|
||||
author = "Fistons <eric@pedr0.net>"
|
||||
authors = ["Fistons <eric@pedr0.net>"]
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
|
|
17
src/main.rs
17
src/main.rs
|
@ -1,17 +1,12 @@
|
|||
#[allow(dead_code)]
|
||||
fn find_peaks_and_valleys(values: &[isize]) -> Vec<usize> {
|
||||
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()
|
||||
.windows(3) // Take three consecutives elements at once
|
||||
.enumerate() // Get the index of the first one
|
||||
.map(|(idx, arr)| (idx, [arr[0], arr[1], arr[2]])) // Map the elements as a fixed size array
|
||||
.filter(|(_, [a, b, c])| (b > a && b > c) || (b < a && b < c)) // Keep if the middle element is peak or valley
|
||||
.map(|(idx, _)| idx + 1) // Map to index of the middle element
|
||||
.collect() // Profit!
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
|
Loading…
Reference in New Issue