main
Eric John Jack Fistons de la Vega 2025-06-11 23:54:18 +02:00
commit f3645427b8
Signed by: fistons
SSH Key Fingerprint: SHA256:qIWjXc6ikLirlS7hO0lQ6g9Ft9Dl2OJ/bZE7R3BA75c
4 changed files with 89 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "peak-and-valley"
version = "0.1.0"

6
Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "peak-and-valley"
version = "0.1.0"
edition = "2024"
[dependencies]

75
src/main.rs Normal file
View File

@ -0,0 +1,75 @@
#[derive(PartialEq, Debug)]
enum Order {
Up,
Down,
Stable,
Uninit,
}
fn find_peaks_and_valleys(values: &[isize]) -> Vec<usize> {
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
}
fn main() {
println!("Hello, world!");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn test() {
assert_eq!(
find_peaks_and_valleys(&[1, 2, 1, 3, 4, 5, 4, 5, 2, 1, 2, 3]),
vec![1, 2, 5, 9]
);
}
#[test]
pub fn test_flat() {
assert_eq!(find_peaks_and_valleys(&[1, 1, 1, 1]), vec![]);
}
#[test]
pub fn test_up_and_down() {
assert_eq!(
find_peaks_and_valleys(&[1, 0, 1, 0, 1, 0]),
vec![1, 2, 3, 4, 5]
);
}
#[test]
pub fn test_negative() {
assert_eq!(
find_peaks_and_valleys(&[-5, -10, -7, -15, -12]),
vec![1, 2, 3]
);
}
}