How to repeat each element of iterator n times?

Viewed 830

I am currently learning Rust, and I stumbled upon an operation for which I can find neither a standard implementation in std nor a reasonably formed snippet of code, which would do what I would like it to do.

Basically I would like to repeat each element of an iterator a given number of times. So for example if a had an iterator of [1,2,3], then by repeating each element 3 times for example I mean that output should be [1,1,1,2,2,2,3,3,3].

How would one do it idiomatically in Rust?

1 Answers

You can use repeat(n).take(n) to repeat the individual elements and flat_map to combine those repetitions into a flat iterator:

let it = vec![1, 2, 3].into_iter();
let repeated = it.flat_map(|n| std::iter::repeat(n).take(3));
assert!(repeated.collect::<Vec<_>>() == vec![1, 1, 1, 2, 2, 2, 3, 3, 3]);

A generic version that converts any iterator into a repeated iterator might look like this (playground):

fn repeat_element<T: Clone>(it: impl Iterator<Item = T>, cnt: usize) -> impl Iterator<Item = T> {
    it.flat_map(move |n| std::iter::repeat(n).take(cnt))
}
Related