我有一个充满字符串的数组,每个字符串都是一个名字。有些名称可能相同,有些名称可能不同。我正在使用的语言是Objective-C。我希望能够从这个数组中找出最受欢迎的名称(该数组将根据用户提供给应用程序的信息而动态显示)。我不确定如何有效地实现这一目标。如果有人可以扩展或提供一个例子,我们将不胜感激。
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.
谢谢
示例:
NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; //james would be the most popular name推荐答案
使用 NSCountedSet ,然后使用 countForObject:方法找到计数最高的对象。
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; } }检查结果:
NSLog(@"Most frequent string: %@ with count: %i", mostOccurringObject,highestCount);信用转到 @ Evan Mulawski 回答
更多推荐
在数组中查找最重复的对象
发布评论