find the range of all elements in an array in rust

To find the range of all elements in an array in Rust, you can iterate over the array and keep track of the minimum and maximum values. Here's an example implementation:

main.rs
fn find_range(arr: &[i32]) -> Option<(i32, i32)> {
    if arr.is_empty() {
        return None;
    }
    
    let mut min = arr[0];
    let mut max = arr[0];
    
    for &num in arr.iter() {
        if num < min {
            min = num;
        }
        if num > max {
            max = num;
        }
    }
    
    Some((min, max))
}

fn main() {
    let arr = [1, 4, -2, 10, 8];
    let range = find_range(&arr);
    println!("Range of {:?}: {:?}", arr, range);
}
470 chars
26 lines

In this example, we define a function find_range that takes an array of i32 as an argument (&[i32]).

The function first checks if the array is empty, returning None if it is. It then initializes two variables, min and max, to the first element of the array.

The function then iterates over the remaining elements of the array, updating the min and max values as necessary.

Finally, the function returns the range as an Option containing a tuple of (i32, i32) representing the minimum and maximum values, respectively.

In the main function, we define an example array and call the find_range function on it, printing the result to the console.

related categories

gistlibby LogSnag