Improvments

main
Eric 2025-06-13 10:29:45 +02:00
parent 9559831318
commit 3446524d70
No known key found for this signature in database
2 changed files with 7 additions and 12 deletions

View File

@ -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"

View File

@ -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() {}