Two Dimensional Iterating

What I am trying to do is iterating over two ranges, so that I could get (for example) every point in a 2D Array (where each nested array has the same length*).

At the moment this code wors fine for me

(0..10).map(move |w| (0..10).map(move |h| (w, h))).flatten()   

but it doesn’t really look too tody. Is there a better way to do this (functiolly)?

To clarify this: I do not want to iterate over a 2D array itself, I want to have an iterator over two iterators

Thank you for taking the time and reading through this :slight_smile:

Have you tried zip?

Tried it a first, but I’ve made a little mistake in my line of reasoning.
I had this code

(0..10).zip.(0..10)

which resulted in an iterator giving me this selection
(0, 0)
(1, 1)
(2, 2)
(3, 3)

Sorry, I read a little too fast, I saw “2 iterators with the same length” and jumped to zip.
I don’t know a simpler way, you might be able to remove the first “move” if you don’t capture anything else, it’s all the help I can give.

How about this:

fn gen_2d_range(from: usize, to: usize) -> impl Iterator<Item = (usize, usize)> {
    (from..to).flat_map(move |a| (from..to).map(move |b| (a, b)))
}

fn main() {
    println!("{:?}", gen_2d_range(0, 5).collect::<Vec<_>>());
}

And if you want (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2) instead, you can change the second from to a (a cross product without duplicates so to say).

1 Like

You can use cartesian_product:

use itertools::Itertools;

fn main() {
    for (x, y) in (0..10).cartesian_product(0..5) {
        println!("{}; {}", x, y);
    }
}
4 Likes

This is perfectly what I have been serching for! Thank you!

using flat_map is the best way to do this, thank you for the response!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.