Finding most repeated object in array

元气小坏坏 提交于 2019-12-05 08:54:24
Paresh Navadiya

Use NSCountedSet and then find the object with highest count using countForObject: method.

//create count set from array
NSCountedSet *setOfObjects = [[NSCountedSet alloc] initWithArray:yourArrayhere];

//Declaration of objects
NSString *mostOccurringObject = @"";
NSUInteger highestCount = 0;

//Iterate in set to find highest count for a object
for (NSString *strObject in setOfObjects)
{
    NSUInteger tempCount = [setOfObjects countForObject:strObject];
    if (tempCount > highest)
    {
        highestCount = tempCount;
        mostOccurringObject = strObject;
    }
}

Checking the result:

NSLog(@"Most frequent string: %@ with count: %i", mostOccurringObject,highestCount);

Credit goes to @Evan Mulawski answer

Samir

I would use a hash table (NSMutableDictionary in your case), go through the array of strings, use each string as key, and set its value as the number its occurrences in the array. You can keep track of the maximum using a variable (or an array of names if there is multiple names with the same number of occurrences).

The running time is then linear ( O(n) where n is the number of names in your array ).

To get the number of occurrences.

NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; 
NSCountedSet *set = [[NSCountedSet alloc] nameArray];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!