Skip to main content

algorithmz/array/
missing_ranges.rs

1/// Find gaps between low and high not covered by elements in array.
2///
3/// Takes a list reference and a low and a high as argument and returns a `Vec(i32,i32)` or an
4/// error explaining the situation.
5///
6/// # Examples
7///
8/// Basic usage:
9/// ```
10/// let result = algorithmz::array::missing_ranges(&[3,5],1,10).unwrap();
11/// assert_eq!(result,vec![(1,2),(4,4),(6,10)]);
12/// ```
13///
14/// Match example:
15/// ```
16/// use algorithmz::array::missing_ranges;
17/// match missing_ranges(&[3,5],1,10) {
18///     Ok(n) => println!("The result was: {:?}",n),
19///     Err(e) => eprintln!("The problems was: {}",e),
20/// }
21/// ```
22pub fn missing_ranges(list: &[i32], low: i32, high: i32) -> Result<Vec<(i32,i32)>,String> {
23    if list.is_empty() {
24        return Err("Cannot use missing ranges on an empty list!".to_string());
25    }
26    let mut result: Vec<(i32,i32)> = Vec::new();
27    let mut start = low;
28    for num in list {
29        if *num == start {
30            start += 1;
31        } else if *num > start {
32            result.push((start, num - 1));
33            start = num + 1;
34        }
35    }
36    if start <= high {
37        result.push((start, high));
38    }
39    Ok(result)
40}
41