Thread overview | ||||||||
---|---|---|---|---|---|---|---|---|
|
August 15, 2011 Re: Split by length? | ||||
---|---|---|---|---|
| ||||
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; } |
August 15, 2011 Re: Split by length? | ||||
---|---|---|---|---|
| ||||
Strings are an exception again, that code won't work for strings. Damn.. |
August 15, 2011 Re: Split by length? | ||||
---|---|---|---|---|
| ||||
On Monday, August 15, 2011 04:49:59 Andrej Mitrovic wrote:
> Is there something in Phobos with which I could do:
>
> auto arr = [1, 2, 3, 4, 5, 6];
>
> int[][] newarr = arr.splitLength(2);
> assert(newarr.length == 3);
I could have sworn that there was a function that did this, but I can't find it at the moment.
- Jonathan M Davis
|
August 15, 2011 Re: Split by length? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andrej Mitrovic | On Sun, 14 Aug 2011 23:00:26 -0400, Andrej Mitrovic <andrej.mitrovich@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
|
August 15, 2011 Re: Split by length? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On 8/15/11, Steven Schveighoffer <schveiguy@yahoo.com> wrote: > Ouch! It's not that big of an ouch actually: http://codepad.org/m1zKlP0e |
August 17, 2011 Re: Split by length? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andrej Mitrovic | Am 15.08.2011, 18:06 Uhr, schrieb Andrej Mitrovic <andrej.mitrovich@gmail.com>:
> On 8/15/11, Steven Schveighoffer <schveiguy@yahoo.com> wrote:
>> Ouch!
>
> It's not that big of an ouch actually: http://codepad.org/m1zKlP0e
Compiled in optimized 64-bit with dmd it gives me:
old: 393 ms
new: 310 ms
which is ~27% overhead. It is an average ouch.
|
Copyright © 1999-2021 by the D Language Foundation