Question

How can I check which value in an NSMutableArray is the most frequent?

Array = "0,2,3,2,2,4

the value = "2".

Was it helpful?

Solution

Take a look at NSCountedSet this will help with your problem.

NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:youArray];

NSInteger maxCount = 0;
id maxObject = nil;

for (id object in countedSet) {
    if ([countedSet object] > maxCount) {
        maxCount = [countedSet countForObject:object];
        maxObject = object;
    }
}

return maxObject;

This does sound like homework though.

EDIT

If they are stored as strings instead of numbers then swap out NSNumber for NSString everything else works the same.

EDIT

Actually, I just realised that it doesn't care about what object type it is...

Latest edit will work whatever the object is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top