DEV Community

loading...

Discussion on: Daily Challenge #278 - Find all non-consecutive numbers

Collapse
idanarye profile image
Idan Arye

Rust:

#[derive(Debug, PartialEq)]
struct IndexAndNumber {
    i: usize,
    n: isize,
}

fn nconsecutive(numbers: &[isize]) -> Vec<IndexAndNumber> {
    let mut it = numbers.iter().enumerate();
    let mut prev = if let Some((_, first_number)) = it.next() {
        *first_number
    } else {
        return Vec::new();
    };
    it.filter_map(|(i, &n)| {
        let is_consecutive = n == prev + 1;
        prev = n;
        if is_consecutive {
            None
        } else {
            Some(IndexAndNumber { i, n })
        }
    }).collect()
}

fn main() {
    assert_eq!(nconsecutive(&[6, 7, 8, 9, 11, 12]), &[
        IndexAndNumber { i: 4, n: 11 }
    ]);
    assert_eq!(nconsecutive(&[100, 101, 102, 112, 113, 114, 129]), &[
        IndexAndNumber { i: 3, n: 112 },
        IndexAndNumber { i: 6, n: 129 },
    ]);
}
Collapse
qm3ster profile image
Mihail Malo
use core::iter::Enumerate;
#[derive(Debug, PartialEq)]
struct IndexAndNumber {
    i: usize,
    n: isize,
}
struct NonCons<I: Iterator<Item = isize>> {
    prev: isize,
    iter: Enumerate<I>,
}
impl<I: Iterator<Item = isize>> NonCons<I> {
    fn new<II: IntoIterator<Item = isize, IntoIter = I>>(it: II) -> Option<Self> {
        let mut iter = it.into_iter().enumerate();
        let prev = iter.next()?.1;
        Some(Self { prev, iter })
    }
}
impl<I: Iterator<Item = isize>> Iterator for NonCons<I> {
    type Item = IndexAndNumber;
    fn next(&mut self) -> Option<Self::Item> {
        for (i, n) in &mut self.iter {
            if (std::mem::replace(&mut self.prev, n) + 1) != n {
                return Some(IndexAndNumber { i, n });
            }
        }
        None
    }
}

fn nconsecutive(numbers: &[isize]) -> Vec<IndexAndNumber> {
    NonCons::new(numbers.into_iter().copied()).unwrap().collect()
}

huhuhu iterator