www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - uniqStable

reply "timotheecour" <timothee.cour2 gmail.com> writes:
can we have something like in std.algorithm ?
it returns uniq elements in original order of appearance

Some cleanup may be needed, please send comments!

auto uniqStable(T)(T a) if(isRandomAccessRange!T){
	return zip(a,iota(a.length)).array.sort!q{a[0] < 
b[0]}.array.uniq!q{a[0]==b[0]}.array.sort!q{a[1]<b[1]}.map!q{a[0]}.array;
}
Mar 18 2013
parent reply "timotheecour" <timothee.cour2 gmail.com> writes:
I forgot unittest:

unittest{
assert(uniqStable([1,3,1,0,2] ==[1, 3, 0, 2] ));
}
of course, it needs template on less, etc.
Mar 18 2013
parent "Andrea Fontana" <nospam example.com> writes:
On Tuesday, 19 March 2013 at 02:09:06 UTC, timotheecour wrote:
 I forgot unittest:

 unittest{
 assert(uniqStable([1,3,1,0,2] ==[1, 3, 0, 2] ));
 }
 of course, it needs template on less, etc.
Stealing reply from Bearophile: http://forum.dlang.org/post/rnsrrlmtguuayfxczsek forum.dlang.org He uses filter2 because filter doesn't cache results, but if you apply distinct() to a range where front() call is "stable" you can use filter.
Mar 19 2013