how to get top N distinct elements from range?

Andrea Fontana nospam at example.com
Fri Mar 8 06:38:20 PST 2013


On Friday, 8 March 2013 at 14:10:55 UTC, bearophile wrote:
> Andrea Fontana:
>
>> I wonder if exists a way to get top n distinct elements from a 
>> range (infinite too!)
>>
>> A (not efficient) way to to this is 
>> range.array.sort.uniq.take(n) but it's a bit overkill, it 
>> sorts elements, and of course doesn't work with infinite 
>> ranges. Am i missing any function?
>
> What does it mean "top"?
>
> I think you are not missing functions.
>
> One solution (not tested):
>
>
> bool[ForeachType!(typeof(myRange))] mySet;
> foreach (item; myRange) {
>     mySet[item] = true;
>     if (mySet.length >= n)
>         break;
> }
> auto top = mySet.byKey;
>
>
> Bye,
> bearophile


Yes I wonder if a lazy function like this function was in phobos. 
It's quite common, and I didn't want to reinvent wheel :)



More information about the Digitalmars-d-learn mailing list