Split a range into equal parts?

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Dec 1 11:18:19 PST 2011


Makeshift terrible implementation:

import std.range;

int[][] split(int[] src, int parts)
{
    int[][] result;
    int len = src.length / parts;

    int iter;
    while (!src.empty)
    {
        if (iter == parts-1)
        {
            result ~= src[];
            break;
        }

        result ~= src[0 .. len];
        src.popFrontN(len);
        iter++;
    }

    return result;
}

void main()
{
    int[] arr = [0, 1, 2, 3, 4, 5, 6, 7];
    assert( arr.split(4) == [[0, 1], [2, 3], [4, 5], [6, 7]] );
}

They don't have to be exactly equal parts, arr could be uneven. So is
there something like this in Phobos that gives me a lazy range
instead?


More information about the Digitalmars-d-learn mailing list