Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over pairs of chunks without creating a temporary vector

Tags:

iterator

rust

I'm trying to iterate a vector as pairs of chunks (in my case it's an image represented as a contiguous bitmap and I'd like to have access to pixels from two rows at once).

The problem is that I can't do .chunks(w).chunks(2), but have to create a temporary vector in between.

Is there a way to do it purely with iterators? (I'm OK if the result is an iterator itself)

playground

let input: Vec<_> = (0..12).collect();

let tmp: Vec<_> = input.chunks(3).collect();
let result: Vec<_> = tmp.chunks(2).collect();

println!("{:?}", result);

[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]

like image 374
Kornel Avatar asked Dec 05 '22 21:12

Kornel


1 Answers

Oh, I've got it! I can split larger chunks:

input.chunks(2*3).map(|dbl| dbl.split_at(3)).collect();

Yes, or you could do this:

let tmp: Vec<_> = input
    .chunks(2 * 3)
    .map(|x| x.chunks(3).collect::<Vec<_>>())
    .collect();

This outputs exactly the same thing as your example, without the mix of tuples and arrays from your solution:

[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
like image 60
Mathieu David Avatar answered Jan 04 '23 07:01

Mathieu David