Last active
          March 11, 2025 04:22 
        
      - 
      
- 
        Save wcheek/4543fc33f97d3931d9214118b08a47b8 to your computer and use it in GitHub Desktop. 
    Checks whether an array of numbers is monotonically increasing or decreasing
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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