Multidimensional arrays, foreach loops and slices

Philippe Sigaud philippe.sigaud at gmail.com
Wed May 30 14:57:45 PDT 2012


On Wed, May 30, 2012 at 6:15 PM, Joseph Rushton Wakeling
<joseph.wakeling at webdrake.net> wrote:
> Hello all,
>
> A couple of queries.  The first I'm sure has been asked/answered
> definitively before, but a search doesn't bring anything up: is it possible
> to foreach() over every element of a multidimensional array, i.e. something
> like,
>
>    int[3][4][5] a;
>
>    foreach(ref int n; a)
>        n = uniform!"[]"(0, 1);
>
> ... or is it necessary to do a separate foreach over each dimension?

When you use foreach on a, it will iterate on a's elements, in this
case the bidimensional subarrays. You'll have to foreach separately on
each dimension to act on individual, scalar, elements.

Of course, D can automate this for you:

module test;

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

template rank(R)
{
    static if (isInputRange!R)
        enum size_t rank = 1 + rank!(ElementType!R);
    else
        enum size_t rank = 0;
}


/**
Maps fun at depth downToRank inside a range of ranges.
*/
auto depthMap(alias fun, int downToRank = 0, R)(R range)
{
    static if (0<= downToRank && downToRank < rank!R)
        return map!(depthMap!(fun, downToRank, ElementType!R))(range);
    else // rank!R == 0 -> range is a scalar, not a range
        return fun(range);
}

int fill(int _) { return uniform!"[]"(0,1);}

void main()
{
    auto r = [[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0]]];
    auto d = depthMap!fill(r);
    writeln(r);
    writeln(d);
}


>
> The second query relates to slices.  Suppose I have an N*M 2d array (let's
> call it a), and a 1d array of length N (let's call it s) whose elements are
> unsigned integers whose values fall in [0, M).  What I'd like is to take a
> slice of a such that I get out a 1d array of length N such that the i'th
> element corresponds to a[s[i]].
>
> Is this possible?  And if so, how is it achieved?

You meant a[i][s[i]], right?


    auto a = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]];
    auto s = [4,3,2];
    auto slice = map!( i => a[i][s[i]])(iota(0,3));
    writeln(slice);

This is a lazy range whose elements are a[i][s[i]]. If you're not
afraid of allocating everything at once, call std.range.array() on it
to transform it into an array:

auto slice2 = array(slice);
writeln(typeof(slice2).stringof);

Philippe


More information about the Digitalmars-d-learn mailing list