Search for most duplicate objects in an array

I have an array full of lines, each line of which is a name. Some names may be the same, and some may be different. The language I work in is objective-C. I want to find out which name is most popular in this array (the array will be dynamic based on the information provided to the user by the user). I'm not sure how to do it EFFECTIVELY. If someone can expand on this or provide an example, this will be appreciated.

thank

Example:

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

  //james would be the most popular name
+5
source share
3 answers

Use NSCountedSetand then find the object with the highest counter using the method countForObject:.

//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;
    }
}

Verification of the result:

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

@Evan Mulawski

+11

- (NSMutableDictionary ), , . ( , ).

(O (n), n - ).

+5

To get the number of occurrences.

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

All Articles