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