Skip to content

Instantly share code, notes, and snippets.

@Japanuspus
Created December 4, 2019 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Japanuspus/b24fb4d0e9a383baf7a0260452d19314 to your computer and use it in GitHub Desktop.
Save Japanuspus/b24fb4d0e9a383baf7a0260452d19314 to your computer and use it in GitHub Desktop.
Create iterator that returns lenghts of runs of identical elements of slice
use std::iter;
fn run_lengths<'a, T>(a: &'a[T]) -> impl Iterator<Item=usize> + 'a
where
T: std::cmp::PartialEq
{
a
.windows(2)
.enumerate()
.filter_map(|(i, ab)| if ab[0]==ab[1] {None} else {Some(i as isize)})
.chain(iter::once(a.len() as isize - 1)) //append edge at end of slice
.scan(-1, |last_pos, pos| { //first edge is before slice
let res = pos - *last_pos;
*last_pos=pos;
Some(res as usize)
})
}
fn main() {
let a = [1,2,3,3,1,1,1];
let r: Vec<_> = run_lengths(&a).collect();
dbg!(&r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment