有谁知道如何获取NSCountedSet对象并按其对象计数按顺序创建这些对象的数组?(最高计数到最低)
我需要在数组中找到最常见的(模态)元素.
我能想到的最简单的方法是为每个唯一元素设置变量,并为每个元素分配一个计数变量,每次在一个贯穿数组的for循环中记录它时,它都会增加.
不幸的是,数组的大小是未知的并且将非常大,因此这种方法是无用的.
我在Objective-C中遇到了一个类似的问题,它使用NSCountedSet方法对数组元素进行排名.不幸的是,我对编程很新,只能将第一行翻译成Swift.
建议的方法如下:
var yourArray: NSArray! // My swift translation
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:yourArray];
NSMutableDictionary *dict=[NSMutableDictionary new];
for (id obj in set) {
[dict setObject:[NSNumber numberWithInteger:[set countForObject:obj]]
forKey:obj]; //key is date
}
NSLog(@"Dict : %@", dict);
NSMutableArray *top3=[[NSMutableArray alloc]initWithCapacity:3];
//which dict obj is = max
if (dict.count>=3) {
while (top3.count<3) {
NSInteger max = [[[dict allValues] valueForKeyPath:@"@max.intValue"] intValue];
for (id obj in set) {
if (max == [dict[obj] integerValue]) {
NSLog(@"--> %@",obj);
[top3 addObject:obj];
[dict removeObjectForKey:obj]; …Run Code Online (Sandbox Code Playgroud) 我迷失在排序描述符,词典和计数集的海洋中.希望有人可以帮我找到一个更简单的方法.
从这样的排序数组开始(NSNumbers):
['7','7','7','5','5','5','5','5','5','3','2','2','2','2']
Run Code Online (Sandbox Code Playgroud)
我想最终得到一个排序的字典数组,如下所示:
{'5','6'} //the number 5 appeared 6 times
{'2','4'} //the number 2 appeared 4 times
{'7','3'} //the number 7 appeared 3 times
{'3','1'} //the number 3 appeared 1 time
Run Code Online (Sandbox Code Playgroud)