Axel0nf1r3 Axel0nf1r3 - 6 months ago 12
iOS Question

NSMutableArray, checking which Value is the most abundant?

How can I check which value in an

is the most frequent?

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


the value = "2".

Answer

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.