Fix challenge
parent
bc586a962f
commit
92225c05db
56
src/main.rs
56
src/main.rs
|
@ -1,44 +1,20 @@
|
||||||
#[derive(PartialEq, Debug)]
|
#[allow(dead_code)]
|
||||||
enum Order {
|
|
||||||
Up,
|
|
||||||
Down,
|
|
||||||
Stable,
|
|
||||||
Uninit,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_peaks_and_valleys(values: &[isize]) -> Vec<usize> {
|
fn find_peaks_and_valleys(values: &[isize]) -> Vec<usize> {
|
||||||
let mut peaks_and_valleys = vec![];
|
values
|
||||||
let mut order = Order::Uninit;
|
.windows(3)
|
||||||
for i in 1..values.len() {
|
.enumerate()
|
||||||
let previous = values[i - 1];
|
.flat_map(|(idx, arr)| {
|
||||||
let current = values[i];
|
let (a, b, c) = (arr[0], arr[1], arr[2]);
|
||||||
|
if (b > a && b > c) || (b < a && b < c) {
|
||||||
let new_order = match current - previous {
|
Some(idx + 1)
|
||||||
0 => Order::Stable,
|
} else {
|
||||||
x if x > 0 => Order::Up,
|
None
|
||||||
x if x < 0 => Order::Down,
|
}
|
||||||
_ => unreachable!(),
|
})
|
||||||
};
|
.collect()
|
||||||
|
|
||||||
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() {
|
fn main() {}
|
||||||
println!("{:?}", find_peaks_and_valleys(&[1, 2, 3, 4, 1, 8]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
@ -47,7 +23,7 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
pub fn test() {
|
pub fn test() {
|
||||||
assert_eq!(
|
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]
|
vec![1, 2, 5, 9]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -61,7 +37,7 @@ mod tests {
|
||||||
pub fn test_up_and_down() {
|
pub fn test_up_and_down() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
find_peaks_and_valleys(&[1, 0, 1, 0, 1, 0]),
|
find_peaks_and_valleys(&[1, 0, 1, 0, 1, 0]),
|
||||||
vec![1, 2, 3, 4, 5]
|
vec![1, 2, 3, 4]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue