How to flatten N-dimensional array?

Ali Çehreli acehreli at yahoo.com
Sat May 23 19:59:30 UTC 2020


On 5/23/20 11:15 AM, Pavel Shkadzko wrote:> I have tried to implement a 
simple flatten function for multidimensional

 > I'd like to clarify a couple of questions first.
 >
 > How come Phobos doesn't have "flatten" function for arrays?

We call in 'joiner'.

I wrote something like this:

import std.stdio;
import std.algorithm;
import std.range;

int value = 0;

auto makeNdim(size_t N)(size_t length)
if (N == 1) {
   auto result = iota(value, value + length).array;
   value += length;
   return result;
}

auto makeNdim(size_t N)(size_t length)
if (N > 1) {
   return iota(N).map!(n => makeNdim!(N - 1)(length)).array;
}

auto flatten(R)(R range)
if (!isInputRange!(ElementType!R)) {
   return range.joiner;
}

auto flatten(R)(R range)
if (isInputRange!(ElementType!R)) {
   return range.map!(r => r.joiner).joiner;
}

void main() {
   auto a = makeNdim!3(5);
   writefln!"Original : %s"(a);
   writefln!"Flattened: %s"(a.flatten);
}

Output:

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, 27, 28, 29]]]
Flattened: [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, 27, 28, 29]

Ali



More information about the Digitalmars-d-learn mailing list