Skip to content

Instantly share code, notes, and snippets.

@wperron
Last active November 8, 2021 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/0f2fda69c7c9206d5f0f287e0f4360aa to your computer and use it in GitHub Desktop.
Save wperron/0f2fda69c7c9206d5f0f287e0f4360aa to your computer and use it in GitHub Desktop.
Function that finds all the local maximas in a vector of unsigned integers
/// Given an array of integers, return the index of each local peak in the array.
/// A “peak” element is an element that is greater than its neighbors.
///
/// Example:
///
/// ```
/// $ localPeaks([1,2,3,1])
/// $ [2]
///
/// $ localPeaks([1,3,2,3,5,6,4])
/// $ [1, 5]
/// ```
fn main() {
let mut max = local_maximas(vec![1, 2, 3, 1]);
println!("{:?}", max);
max = local_maximas(vec![1, 3, 2, 3, 5, 6, 4]);
println!("{:?}", max);
}
fn local_maximas(nums: Vec<usize>) -> Option<Vec<usize>> {
match nums.len() {
0 => return None,
1 => return Some(vec![0]),
_ => {}
};
let mut max: Vec<usize> = Vec::new();
let mut prev = usize::MIN;
let mut last: &[usize] = &vec![];
for (i, n) in nums.windows(2).enumerate() {
if prev < n[0] && n[0] > n[1] {
max.push(i);
}
prev = n[0];
last = n.clone();
}
// Handle the last element as a special due to how the `windows` API from
// itertools work.
if last[1] > last[0] {
max.push(nums.len() - 1);
}
match max.len() {
0 => None,
_ => Some(max),
}
}
#[cfg(test)]
mod tests {
use super::local_maximas;
#[test]
fn it_works() {
assert_eq!(local_maximas(vec![1, 2, 3, 1]), Some(vec![2]));
assert_eq!(local_maximas(vec![1, 3, 2, 3, 5, 6, 4]), Some(vec![1, 5]));
assert_eq!(local_maximas(vec![1, 2, 3, 4]), Some(vec![3]));
assert_eq!(local_maximas(vec![4, 3, 2, 1]), Some(vec![0]));
assert_eq!(local_maximas(vec![9]), Some(vec![0]));
assert_eq!(local_maximas(vec![]), None);
// special case where there is a plateau instead of a peak
assert_eq!(local_maximas(vec![1, 2, 2, 2, 1]), None);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment