Alex G
Alex G

Reputation: 2309

Finding most repeated object in array

I have an array full of strings with each string being a name. Some names may be the same while some may be different. The language I'm working in is objective-C. I want to be able to find out which name is most popular from this array (the array will be dynamic based on information given to the app from the user). I am not sure how to make this happen EFFICIENTLY. If someone could expand on this or provide an example, it would be appreciated.

Thank you

Example:

NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; 

  //james would be the most popular name

Upvotes: 5

Views: 3820

Answers (3)

Franck
Franck

Reputation: 9359

To get the number of occurrences.

NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; 
NSCountedSet *set = [[NSCountedSet alloc] nameArray];

Upvotes: 0

Samir
Samir

Reputation: 627

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 ).

Upvotes: 5

Paresh Navadiya
Paresh Navadiya

Reputation: 38249

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

Upvotes: 11

Related Questions