DEV Community

loading...

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

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