On Friday, 8 March 2013 at 15:53:56 UTC, Andrea Fontana wrote:
On Friday, 8 March 2013 at 14:43:29 UTC, jerro wrote:
On Friday, 8 March 2013 at 13:33:24 UTC, Andrea Fontana wrote:
I wonder if exists a way to get top n distinct elements from
a range (infinite too!)
It's impossible to do that for infinite ranges
Why?
sequence!"n*2".myTopDistinct!"a==b"(3);
will give [2,4,6]
I didn't understand you correctly then. I thought that top n
distinct elements meant n largest distinct elements. Now, I'm
assuming that you just need first n distinct elements.
We just need to keep a list of "just-seen" elements
But I don't know how to make it lazy
You could write your own range that uses an associative array to
check for duplicates:
struct Unique(R)
{
R r;
bool[elementType!R] seen;
@property front(){ return r.front; }
@property empty(){ return r.empty; }
void popFront()
{
seen[r] = bool.init;
while(r.front in seen)
r.popFront();
}
}
I don't think there's anything like this in Phobos.