首先,让我们定义一个方便的元组类型,我们可以使用它来将一个数字与其出现次数相关联:
@interface Pair : NSObject
@property(nonatomic, strong) id key;
@property(nonatomic, strong) id value;
- (id)initWithKey:(id)key value:(id)value;
@end
@implementation Pair
- (id)initWithKey:(id)key value:(id)value;
{
if((self = [super init])) {
_key = key;
_value = value;
}
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"(%@,%@)", self.key, self.value];
}
@end
然后,为了获得所需的结果,使用计数集来计算出现次数,然后将结果填充到元组数组中并按出现次数排序。
- (void)testOccurrenceCounting
{
NSArray *numbers = @[@1, @3, @4, @6, @6, @3, @1, @3];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:numbers];
NSMutableArray *counters = [NSMutableArray arrayWithCapacity:[set count]];
[set enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
[counters addObject:[[Pair alloc] initWithKey:obj value:@([set countForObject:obj])]];
}];
[counters sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"value" ascending:YES]]];
NSLog(@"%@", counters);
}
counters
现在是一个排序的Pair
对象数组,其中key
属性保存数字,value
属性保存出现次数,两者都装箱为NSNumbers
. 从那里,您可以将它们拆箱或按您认为合适的方式操作集合。
作为有效的证明,下面是NSLog
语句的输出:
(
"(4,1)",
"(6,2)",
"(1,2)",
"(3,3)"
)