Linear array to matrix

p.shkadzko p.shkadzko at gmail.com
Sun Apr 5 18:58:17 UTC 2020


On Saturday, 4 April 2020 at 09:25:14 UTC, Giovanni Di Maria 
wrote:
> Hi.
> Is there a Built-in function (no code, only a built-in function)
> that transform a linear array to a Matrix?
>
> For example:
>
> From
>
> [10,20,30,40,50,60,70,80,90,100,110,120];
>
>
> To
>
> [
> [10,20,30],
> [40,50,60],
> [70,80,90],
> [100,110,120]
> ];
>
> Thank You very much
> Cheers.
> Giovanni

Why not use "chunks" from std.range?

import std.range: chunks;

void main() {
     int[] arr = [10,20,30,40,50,60,70,80,90,100,110,120];
     auto matrix1 = arr.chunks(3).chunks(4); // no allocation
     int[][][] matrix2 = arr.chunks(3).array.chunks(4).array;
}

But, keep in mind using array of arrays is not efficient.
For multidimensional arrays use Mir Slices.
If you need more information on how to create matrices, see this 
article: 
https://tastyminerals.github.io/tasty-blog/random/2020/03/22/multidimensional_arrays_in_d.html




More information about the Digitalmars-d-learn mailing list