Remove Duplicates in Array

666 views
Skip to first unread message

varomix DaGreit

unread,
Dec 28, 2011, 12:45:17 AM12/28/11
to haxe...@googlegroups.com
HI guys
another question

how can I remove duplicate entries in an array, I only want unique numbers
I had this working in AS3 but can't make it work on haxe seems I was using
the indexOf function in an array.

this is what I want, if I have this array
[12. 34, 23, 54, 12, 34, 44, 556]

I want to delete all duplicates
[12. 34, 23, 54, 44, 556]

Thanks

Marc Weber

unread,
Dec 28, 2011, 1:04:40 AM12/28/11
to haxelang
Excerpts from varomix DaGreit's message of Wed Dec 28 06:45:17 +0100 2011:
> HI guys
> another question

way 1): search a library providing such a function
way 2a): do it manually iterating over all indices (preserve order)
way 2b): do it like 2a) in some way but use ints as keys for hashes
because lookup "seen" might be faster. For that size a simple loop will
suffice.

Have a look at Lambda.hx which applies whenever something is "iterable".
It does not have an unique function yet.

Using "using" you can then do
[1,1].unique();

So consider looking "using" up in online docs. Thus something like this
is probably best you can do (if you don't have very long arrays):

using Lambda;
class MyArrayExtenison {
static public function unique<T>(x:Array<T>, f: T -> T -> Bool):Array<T>{
var r = [];
for (e in x){
if (!r.exists(e, f)) // you can inline exists yourself if you care much about speed. But then you should consider using hash tables or such
r.push(e);
}
return r;
}
}

Marc Weber

Tarwin Stroh-Spijer

unread,
Dec 28, 2011, 2:39:08 AM12/28/11
to haxe...@googlegroups.com
You'l probably be a little over your head to begin with to understand the above fully, but you'll get there.

 function unique<T>(x:Array<T>, f: T -> T -> Bool):Array<T> 

To get you started: the above uses generics. It defines "T" as a type that you want to use ie the Class that you want to be able to send in. So say you use it like this as your function:

var myFunc = function(a:String, b:String):Bool;

And call unique like this:

unique( [ "hello", "world" ], myFunc);

Here, "T" would be a "String". The f:T->T->Bool means it takes a function that takes T and T and returns a Bool (any function with that signature).

Hope that helps some.


Tarwin Stroh-Spijer
_______________________

Touch My Pixel
http://www.touchmypixel.com/
phone: +61 3 8060 5321
_______________________


varomix DaGreit

unread,
Dec 28, 2011, 11:36:18 PM12/28/11
to haxe...@googlegroups.com
That is kinda what I'm doing in as3
so that might work

thanks for the help awesome!!
Reply all
Reply to author
Forward
0 new messages