On Friday, 22 January 2016 at 12:07:11 UTC, abad wrote:
Let's say I have an array like this:

int[][][] array;

And I want to generate a linear int[] based on its data. Is there a standard library method for achieving this, or must I iterate over the array manually?

What I'm thinking of is something like this:

int[] onedim = std.array.collapse(array);

It's not the thing you want but I would suggest using one dimensional array like N dimensional array like this:

        int d1 = 10, d2 = 10, d3 = 10;
        int[] arr = new int[d1 * d2 * d3];
        for(int i = 0; i < d1; i++)
                for(int j = 0; j < d2; j++)
                        for(int k = 0; k < d3; k++)
                                write(arr[(i * d1 * d2) + (j * d2) + (k)]);

This will lead to cache friendly code in most cases as you ensure data is packed. It's elements can be iterated with a single foreach loop and easier to use in some (many?) cases like when using functions that works with one dimensional array.

And if you seriously need multi dimensional array then it's too easier to do it yourself:

        int[][][] a = new int[][][](d1, d2, d3);
        int[] collapsed = new int[d1 * d2 * d3];
        foreach(i, q; a)
                foreach(j, w; q)
                        foreach(k, e; w)
                                collapsed[(i * d1 * d2) + (j * d2) + (k)] = e;

Reply via email to