On Tuesday, 10 May 2016 at 15:18:50 UTC, ZombineDev wrote:
On Tuesday, 10 May 2016 at 10:21:30 UTC, ZombineDev wrote:

(You can try it at: https://dpaste.dzfl.pl/c0327f067fca)

import std.array : array;
import std.experimental.ndslice : byElement, indexSlice, sliced;
import std.range : iota, lockstep, zip;
import std.stdio : writefln;

void main()
{
    // needs .array for ref (lvalue) access
    // (iota offers only rvalues)
    auto slice = iota(2 * 3 * 4).array.sliced(2, 3, 4);

    auto indexed_range = lockstep(
        slice.shape.indexSlice.byElement(),
        slice.byElement()
    );

    writefln("%s", slice);

    foreach (idx, ref elem; indexed_range)
        writefln("Element at %s = %s", idx, ++elem);
}


The code above is slow because it calculates index using multiple assembler ops.

Following would be faster:

for(auto elems = slice.byElement; !elems.empty; elems.popFront)
{
    size_t[2] index = elems.index;
    elems.front = index[0] * 10 + index[1] * 3;
}

For really fast code just use multiple foreach loops:

foreach(i; matrix.length)
{
    auto row = matrix[i]; // optional
    foreach(j; matrix.length!1)
    {
        ...
    }
}

Reply via email to