【问题标题】:Sorting an array by number of times an object appears in that array按对象在该数组中出现的次数对数组进行排序
【发布时间】:2013-05-07 17:37:30
【问题描述】:

我迷失在分类描述符、字典和计数集的海洋中。希望有人可以帮助我找到更简单的方法。

从这样的排序数组开始(NSNumbers):

['7','7','7','5','5','5','5','5','5','3','2','2','2','2']

我希望得到一个排序后的字典数组,如下所示:

{'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

【问题讨论】:

  • 你提到的字典无效要不要{@"Number":5, @"Repeat":6}
  • 有效。键是 NSNumber,值是它在数组中出现次数的 NSNumber。
  • 我现在无法编辑我的评论,它是有效的,但如果你这样存储它的可用性会很困难。你的字典的键应该总是已知的。使用这种结构,您始终可以使用描述符进行排序并找到带有谓词的数字。

标签: ios nsarray nsdictionary nssortdescriptor nscountedset


【解决方案1】:

这是一个基于 NSCountedSet 的 sn-p 功能

NSArray *numbers = @[@7,@7,@7,@5,@5,@5,@5,@5,@5,@3,@2,@2,@2,@2];

NSCountedSet *countedSet = [NSCountedSet setWithArray:numbers];

NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSNumber *num in countedSet) {
    NSUInteger c = [countedSet countForObject:num];
    [result setObject:@(c) forKey:num];
}

【讨论】:

    猜你喜欢
    • 2015-08-28
    • 2023-03-13
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    相关资源
    最近更新 更多