Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to check if a vector is all increasing or decreasing and the gap between numbers is 1, 2 or 3 in Rust

1 Answer

0 votes
use std::f64;

fn is_array_sorted_and_valid_gap(vec: &[i32]) -> bool {
    if vec.len() < 2 {
        return true;
    }

    let increasing = vec[1] > vec[0];
    for i in 1..vec.len() {
        let diff = (vec[i] - vec[i - 1]).abs() as f64;
        if diff < 1.0 || diff > 3.0 {
            return false;
        }
        if (increasing && vec[i] <= vec[i - 1]) || (!increasing && vec[i] >= vec[i - 1]) {
            return false;
        }
    }
    
    true
}

fn main() {
    let vec1 = vec![1, 2, 3, 5, 8, 11, 14, 15];
    println!("{}", is_array_sorted_and_valid_gap(&vec1)); 

    let vec2 = vec![15, 14, 11, 8, 5, 3, 2, 1];
    println!("{}", is_array_sorted_and_valid_gap(&vec2)); 

    let vec3 = vec![1, 2, 300, 5, 8, 11, 14, 15];
    println!("{}", is_array_sorted_and_valid_gap(&vec3)); 
}


  
/*
run:
  
true
true
false
 
*/

 



answered Jan 13, 2025 by avibootz
...