Created
December 4, 2019 15:02
-
-
Save Japanuspus/b24fb4d0e9a383baf7a0260452d19314 to your computer and use it in GitHub Desktop.
Create iterator that returns lenghts of runs of identical elements of slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Playground at https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=713a989f351f9474c59c1cf12df4e7d1