Reducing an array

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 18 15:11:16 PDT 2014


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


More information about the Digitalmars-d-learn mailing list