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,966 questions

51,908 answers

573 users

How to find the floor and ceiling of the value N in an unsorted vector with Rust

1 Answer

0 votes
fn find_floor_and_ceil(vec: &[i32], n: i32) -> (i32, i32) {
    let mut floorval = i32::MIN; // Initialize to smallest possible value
    let mut ceilval = i32::MAX;  // Initialize to largest possible value

    for &num in vec {
        if num <= n && num > floorval {
            floorval = num; // Update floorval if num is closer to n
        }
        if num >= n && num < ceilval {
            ceilval = num; // Update ceilval if num is closer to n
        }
    }

    // If no valid floorval or ceilval is found, set them to a special value
    if floorval == i32::MIN {
        floorval = -1;
    }
    if ceilval == i32::MAX {
        ceilval = -1;
    }

    (floorval, ceilval)
}

fn main() {
    let vec = vec![4, 10, 8, 2, 6, 9, 1];
    let n = 5;

    let (floorval, ceilval) = find_floor_and_ceil(&vec, n);

    println!("floor: {}", if floorval == -1 { "None".to_string() } else { floorval.to_string() });
    println!("ceil: {}", if ceilval == -1 { "None".to_string() } else { ceilval.to_string() });
}



/*
run:

floor: 4
ceil: 6

*/

 



answered Nov 8, 2025 by avibootz
...