views:

52

answers:

2

I've got an array (actually a mutable array) of NSStrings, and I want to find out how many unique elements the are in the array.

For instance, say the array is made up of:

Orange, Lemon, Lemon, Orange, Lemon

Then there are just two unique elements (Orange and Lemon). And this array:

Paul, Steve, John, Harry, Paul, John

..has four unique unique elements.

How do I discover this number?

+9  A: 

NSSet can't contain equal objects, so the following works:

NSUInteger count = [[NSSet setWithArray:array] count];
JoostK
+1  A: 

Do a linear scan of the array, and, for each element, add it to an NSMutableSet. Finally count the number of elements in the NSMutableSet. The NSMutableSet will not allow adding a repeated element.

This is faster then sorting the array, and then doing a linear scan incrementing a variable each time you discover a new element.

EDIT: the implementation in Objective-C has been provided by JoostK.

unforgiven