Skip to content

Instantly share code, notes, and snippets.

@wcheek
Last active March 11, 2025 04:22
Show Gist options
  • Save wcheek/4543fc33f97d3931d9214118b08a47b8 to your computer and use it in GitHub Desktop.
Save wcheek/4543fc33f97d3931d9214118b08a47b8 to your computer and use it in GitHub Desktop.
Checks whether an array of numbers is monotonically increasing or decreasing
fn is_monotonic(data: &[u32]) -> bool {
if data.len() <= 2 {
return true;
}
let direction = data[1].cmp(&data[0]);
for i in 2..data.len() {
if breaks_direction(direction, data[i], data[i - 1]) {
return false;
}
}
true
}
fn breaks_direction(direction: Ordering, current: u32, previous: u32) -> bool {
let difference = current.cmp(&previous);
if direction != difference {
return true;
}
false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment