我如何计算和排序NSMutableArray重复值

时间:2013-09-03 21:49:33

标签: objective-c sorting nsmutablearray nsarray

我见过这个问题:
    NSMutableArray counting occurances of objects and then re-arange the array

解决方案非常接近我需要的。

我所指的解决方案:

NSInteger countedSort(id obj1, id obj2, void *context) {
   NSCountedSet *countedSet = context;
   NSUInteger obj1Count = [countedSet countForObject:obj1];
   NSUInteger obj2Count = [countedSet countForObject:obj2];

   if (obj1Count > obj2Count) return NSOrderedAscending;
   else if (obj1Count < obj2Count) return NSOrderedDescending;
   return NSOrderedSame;
}    

NSMutableArray *array = …;

NSCountedSet *countedSet = [[[NSCountedSet alloc] initWithArray:array]
autorelease];

[array sortUsingFunction:countedSort context:countedSet];    

sort按计数返回正确的排序数组,但是我需要包含或在另一个按升序排序的数组中计数。

2 个答案:

答案 0 :(得分:1)

解决方案可以是简单地查询计数集中的任何对象的计数,以构建一个跟踪计数的数组:

// This after having sorted the array:
NSMutableArray* counts= [NSMutableArray arrayWithCapacity: array.count];
for(id object in array) {
    [counts addObject: @([countedSet countForObject: object]) ];
}

答案 1 :(得分:0)

返回按最大值

排序的排序数组
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];

NSArray *sortedValues = [countedSet.allObjects sortedArrayUsingComparator:^(id obj1, id obj2) {
    NSUInteger n = [countedSet countForObject:obj1];
    NSUInteger m = [countedSet countForObject:obj2];
    return (n <= m)? (n < m)? NSOrderedDescending : NSOrderedSame : NSOrderedAscending;
}];