Question

This is a core function question. I always dealt with this problem on the database side, by I can't do it for this case and I am stumped. I want to count the distinct values. Let's say I have an array

Array = {a,a,a,a,b,b,b,b,c,c,c,c}

And what I want is simply to get

Result = {[a,4],[b,4],[c,4]}  or

ResultDistinct = { a, b, c} , ResultCount = {4,4,4}

I am fine with whatever format as long as it is fast and neat.

Was it helpful?

Solution

Use NSCountedSet.

NSArray *myArray = ... // array with all the a, b, and c values
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:myArray];
for (id obj in set) {
    NSLog(@"There are %d instances of %@", [set countForObject:obj], obj);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top