Fix challenge

main
Eric John Jack Fistons de la Vega 2025-06-12 22:34:50 +02:00
parent bc586a962f
commit 92225c05db
Signed by: fistons
SSH Key Fingerprint: SHA256:qIWjXc6ikLirlS7hO0lQ6g9Ft9Dl2OJ/bZE7R3BA75c
1 changed files with 16 additions and 40 deletions

View File

@ -1,44 +1,20 @@
#[derive(PartialEq, Debug)]
enum Order {
Up,
Down,
Stable,
Uninit,
}
#[allow(dead_code)]
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
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]
);
}