Working with arrays (flatten, transpose, verfify rectangular)

anonymouse anony at mouse.com
Wed Jul 20 09:18:29 UTC 2022


     Given an array of arbitrary dimensions, I would like to 
accomplish three things:
         1) verify that it is rectangular (e.g. all elements have 
the same length, all sub-elements have the same length, etc.)
         2) flatten and return the flattened copy
         3) transpose and return the transposed copy

Here is my naive attempt to accomplish the first task:

         ````d
         auto isRectangular(A)(A a) if (isArray!A)
         {
             bool result;
             size_t length = a[0].length;

             foreach (e; a) {
                 result = e.length == length;
             }
             return result;
         }
         ````

This only works if ````a```` is a 2D array, how do I extend this 
to support arrays with larger dimensions (3D, 4D, 5D, etc.)?

For task 3, I can visit each element of the array, but I have no 
idea how to compose the flattened (1D) version:

         ````d
         import std.range.primitives: ElementType;
         auto flatten(A)(A a) if (isArray!A)
         {
             //ElementType!(A)[] result; //[1]
             foreach (i; a) {
                 static if (isArray!(typeof(i)))
                    flatten(i);
                 else {
                     writeln(i);
                     // result ~= i; //[2]
                 }
             }
             //return result; // [3]
         }
         ````

The thought I had was to get the BaseType of the array (int, 
double, etc.) and use it to create a dynamic array [1]. I could 
then concatenate each element [2], and return the result once 
completed [3]. This approach has two major problems and probably 
many other's I'm not yet experienced enough to see. The first is 
that there's no way to get the BaseType of an array. ElementType 
in the example assumes that array is 2D, therefore anything else 
passed in will result in a multi-dimensional array being created 
to which individual elements cannot be concatenated. The second 
issue is that each call to flatten will have it's own result 
which will be discarded when the function exits, so the final 
result will be an empty array.

As for task 3, while I understand the concept of transposing a 
matrix, I'm not sure how to even begin.

These tasks are all self assigned and not associated with any 
high school or college course. Just trying get a better 
understanding of how arrays and matrices/tensors work while 
reading up on linear algebra. This is purely self study and I 
would really appreciate some assistance.

Thanks,
---anonymouse


More information about the Digitalmars-d-learn mailing list