Collapsing n-dimensional array to linear (1 dimensional)
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 22 23:57:55 PST 2016
On 01/22/2016 04:07 AM, 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);
>
>
Something feels extra down there but it seems to work. :)
import std.stdio;
import std.range;
import std.algorithm;
auto collapse(R)(R r)
if (isArray!R) {
return r.joiner.collapse.joiner;
}
auto collapse(R)(R r)
if (!isArray!R) {
return r;
}
unittest {
auto r = 3.iota
.map!(i => iota(3 * i, 3 * i + 3)
.map!(j => iota(3 * j, 3 * j + 3)
.array)
.array)
.array;
writeln("Original:\n", r);
writeln("\nCollapsed:\n", r.collapse);
assert(r.collapse.equal(iota(27)));
}
void main() {
}
Original:
[[[0, 1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16,
17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]
Collapsed:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26]
Ali
More information about the Digitalmars-d-learn
mailing list