Reducing an array
monarch_dodra via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Apr 19 05:43:41 PDT 2014
On Friday, 18 April 2014 at 22:11:17 UTC, bearophile wrote:
> monarch_dodra:
>
>> Out of curiosity, if the requirement was to *also* preserve
>> ordering (eg: remove all non-first elements), how would you go
>> at it?
>>
>> [2, 1, 1, 3, 2, 3] => [2, 1, 3];
>>
>> Maybe std.algorithm's `makeIndex` would help here?
>>
>> Bonus points for doing it inplace.
>
> This preserves ordering and it's in-place. Not tested much:
>
> void main() {
> import std.stdio, std.traits;
>
> auto data = [2, 1, 1, 3, 2, 3];
>
> bool[ForeachType!(typeof(data))] seen;
> size_t pos = 0;
> foreach (immutable i; 0 .. data.length)
> if (data[i] !in seen) {
> if (pos != i)
> data[pos] = data[i];
> seen[data[i]] = true;
> pos++;
> }
> data.length = pos;
>
> data.writeln;
> }
>
>
> Bye,
> bearophile
I thought of an approach somewhere along these lines. I was
wondering if there was a UFCS approach too. Or an in-place
approach.
Well, the "inplace" is easy of you accept N² performance :)
More information about the Digitalmars-d-learn
mailing list