Collapsing n-dimensional array to linear (1 dimensional)

Xinok via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 22 06:18:29 PST 2016


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);

You can use std.algorithm.joiner but you have to call it twice to 
flatten a 3D array to a 1D array.

     import std.algorithm, std.stdio, std.array;

     void main()
     {
         int[][][] arr = [[[1], [2, 3]], [[4, 5], [6, 7]], [[8], 
[9, 10], [11]]];
         int[] arr2 = arr.joiner.joiner.array;
         writeln(arr);
         writeln(arr2);
     }

http://dlang.org/phobos/std_algorithm_iteration.html#.joiner


More information about the Digitalmars-d-learn mailing list