how to get top N distinct elements from range?

bearophile bearophileHUGS at lycos.com
Fri Mar 8 10:17:19 PST 2013


> Otherwise return an impure take of a filter closure from a 
> function that keeps the set. Something like (untested):

It seems to work:



import std.stdio, std.range, std.algorithm, std.traits;

auto firstDistinct(Range)(Range r, in size_t n) {
     bool[ForeachType!Range] mySet;

     return r.filter!((k) {
         if (k in mySet)
             return false;
         mySet[k] = true;
         return true;
     }).take(n);
}

void main() {
     immutable data = [1, 0, 0, 0, 0, 3, 3, 0, 3, 3, 0, 2, 3, 2, 
3, 2,
                       3, 1, 1, 3, 2, 1, 0, 0, 0, 1, 0, 3, 0, 3];
     foreach (i; 0 .. 6)
         data.firstDistinct(i).writeln;
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list