在数组中查找最重复的对象 [英] Finding most repeated object in array

查看:134
本文介绍了在数组中查找最重复的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个充满字符串的数组,每个字符串都是一个名字。有些名称可能相同,有些名称可能不同。我正在使用的语言是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 回答

这篇关于在数组中查找最重复的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆