Split by length?
Steven Schveighoffer
schveiguy at yahoo.com
Mon Aug 15 07:07:26 PDT 2011
On Sun, 14 Aug 2011 23:00:26 -0400, Andrej Mitrovic
<andrej.mitrovich at gmail.com> wrote:
> Simplified (and slow) implementation:
>
> T[] splitLength(T)(T arr, size_t count) if (isArray!T)
> {
> T[] result;
>
> while (arr.length)
> {
> result ~= arr.take(count);
> arr.popFrontN(count);
> }
>
> return result;
> }
Ouch!
Slicing is your friend :) Also, threw in a reserve for good measure, and
you really need an assert to ensure count is not 0:
assert(count > 0);
result.reserve((arr.length + count - 1) / count)
while(arr.length > count)
{
result ~= arr[0..count];
arr = arr[count..$];
}
if(arr.length)
result ~= arr;
-Steve
More information about the Digitalmars-d-learn
mailing list