Working with arrays (flatten, transpose, verfify rectangular)

anonymouse anony at mouse.com
Fri Jul 22 01:57:47 UTC 2022


On Wednesday, 20 July 2022 at 16:15:33 UTC, Salih Dincer wrote:
> On Wednesday, 20 July 2022 at 09:18:29 UTC, anonymouse wrote:
>>     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
>
> Yesterday, I published an example of a lesson we developed with 
> Ali.  It's same `transpose()` when I add extra `swap()` for 
> you.  I hope it works for you.
>

Hello Salih, thanks for responding. I'm not seeing the transpose 
function here. What I meant by transpose is, given the following:

```d
auto array = [
    [111, 112, 113, 114],
    [121, 122, 123, 124],
    [131, 132, 133, 134],
    [141, 142, 143, 144]
]
```

after applying transpose(), you'd get back the following in 
return:

     [
         [111, 121, 131, 141],
         [112, 122, 132, 142],
         [113, 123, 133, 143],
         [114, 124, 134, 144]
     ]

This should scale to arrays of all dimensions, so the row vector 
(1D array):

     [100, 200, 300, 4000]

would transpose to:

     [[100],
      [200],
      [300],
      [400]]

In general, the transpose of any array yields an array with its 
shape reversed. For example, the following array of shape [2, 4, 
5]:

```d
auto array = [[
    [111, 112, 113, 114, 115],
    [121, 122, 123, 124, 125],
    [131, 132, 133, 134, 135],
    [141, 142, 143, 144, 145]
], [
    [211, 212, 213, 214, 125],
    [221, 222, 223, 224, 225],
    [231, 232, 233, 234, 235],
    [241, 242, 243, 244, 245]
]]
```

would become this array of shape [5, 4, 2] after transpose, with 
its columns becoming its rows and its rows becoming its columns:

```d
[[[111, 211],
   [121, 221],
   [131, 231],
   [141, 241]],
  [[112, 212],
   [122, 222],
   [132, 232],
   [142, 242]],
  [[113, 213],
   [123, 223],
   [133, 233],
   [143, 243]],
  [[114, 214],
   [124, 224],
   [134, 234],
   [144, 244]],
  [[115, 215],
   [125, 225],
   [135, 235],
   [145, 245]]]
```

Thanks,
--anonymouse


More information about the Digitalmars-d-learn mailing list