Iterate over pairs of pieces without creating a temporary vector

I am trying to iterate over a vector in the form of pairs of pieces (in my case, this is an image presented as a continuous bitmap, and I would like to have access to pixels from two lines at once).

The problem is that I cannot execute .chunks(w).chunks(2), but must create a temporary vector between them.

Is there a way to do this exclusively with iterators? (I'm fine 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]]]

+4
source share
4 answers

Oh, I have it! I can split the big chunks:

input
   .chunks(2 * 100)
   .map(|pair| pair.split_at(100))
+3
source

, , . , .zip(), , :

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

    let it1 = input
        .chunks(3)
        .enumerate()
        .filter_map(|x| if x.0 % 2 == 0 { Some(x.1) } else { None });
    let it2 = input
        .chunks(3)
        .enumerate()
        .filter_map(|x| if x.0 % 2 != 0 { Some(x.1) } else { None });

    let r: Vec<_> = it1.zip(it2).collect();

    println!("{:?}", r);
}
+4

chunk(a).chunk(b) , chunk() , chunk() (a Chunk) . , , Iterator. (, ?)

, - (.. ++- ), itertools, batching(). , , chunk(2), , :

extern crate itertools;

use itertools::Itertools;

fn main() {
    // An adaptor that gathers elements up in pairs
    let pit = (0..4).batching(|it| match it.next() {
        None => None,
        Some(x) => match it.next() {
            None => None,
            Some(y) => Some((x, y)),
        },
    });

    itertools::assert_equal(pit, vec![(0, 1), (2, 3)]);
}
+3

Oh, I have it! I can split the big 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 as your example, without combining tuples and arrays from your solution:

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

All Articles