Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to iterate over multidimensional array?

I have a dynamic 3d array of numbers and currently I'm doing it like I usually would in C:

for (auto i = 0; i < size; i++) {
    for (auto j = 0; j < size; j++) {
        for (auto k = 0; k < size; k++) {
            ...
        }
    }
}

Looks pretty ugly. Is there a shorter and maybe more "elegant" way of doing this in D?

like image 491
szx Avatar asked Feb 19 '11 07:02

szx


People also ask

How do you iterate through a multidimensional array?

In order to loop over a 2D array, we first go through each row, and then again we go through each column in every row. That's why we need two loops, nested in each other. Anytime, if you want to come out of the nested loop, you can use the break statement.

What type of loop is the most appropriate for iterating a 2D array?

We explored using for loops with one-dimensional arrays. Now let's jump into nested for loops as a method for iterating through 2D arrays. A nested for loop is one for loop inside another.

Can you use an enhanced for loop on a 2D array?

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.

Can we use for each loop for multidimensional array in Java?

To loop over two dimensional array in Java you can use two for loops. Each loop uses an index. Index of outer for loop refers to the rows, and inner loop refers to the columns. You can then get each element from the array using the combination of row and column indexes.


1 Answers

Using foreach is probably most idiomatic approach in D. It is possible to iterate by both index and value or value only.

import std.stdio;

void main () {

auto arr3 = [ [[1 ,2 ,3 ]], [[4 ,5 ,6 ]], [[7 , 8, 9]], 
              [[11,12,13]], [[14,15,16]], [[17,18,19]] ];

    foreach (index3, arr2; arr3)
    foreach (index2, arr1; arr2)
    foreach (index1, val ; arr1) {
        assert (val == arr3[index3][index2][index1]);
        writeln (val);
    }
}
like image 71
Michal Minich Avatar answered Sep 30 '22 14:09

Michal Minich