Remove duplicates

Namespace rswhite4 at googlemail.com
Tue May 21 15:45:06 PDT 2013


On Tuesday, 21 May 2013 at 22:00:09 UTC, bearophile wrote:
> Sometimes I have need a simple function like this, related to 
> std.string.squeeze:
>
>
> // Must keep the original order of the items.
> // Slow implementation that shows the semantics.
> T[] noDupes(T)(in T[] s) {
>     import std.algorithm: canFind;
>     T[] result;
>     foreach (T c; s)
>         if (!result.canFind(c))
>             result ~= c;
>     return result;
> }
>
> void main() {
>     import std.string: squeeze;
>     assert("AAAA".noDupes == "A");
>     assert("AAAA".squeeze == "A");
>     assert("ABAC".noDupes == "ABC");
>     assert("ABAC".squeeze == "ABAC");
> }
>
>
> Do you know if this function (or a simple way to implement it) 
> already in Phobos?
>
> Bye,
> bearophile

I would prefer a map solution like this:

----
@property
T[] noDupes(T)(const T[] arr) {
     bool[T] map;

     foreach (T item; arr) {
         if (item !in map)
             map[item] = true;
     }

     return map.keys;
}
----

I do not know if this solution would be much faster. But if I 
should make a statement, I would tend to yes.


More information about the Digitalmars-d-learn mailing list