按频率排序数组?

时间:2015-08-10 22:47:45

标签: objective-c sorting

在目标c中按频率对字符串数组进行排序的最佳方法是什么?另外,如果频率之间存在联系,我想按字母顺序排序。我想删除重复项。

我可以想办法做到这一点,只是不确定最佳方式是什么。

[" b"," a"," b"," c"," b"] - > [" B"""" C"]

3 个答案:

答案 0 :(得分:1)

听起来你想要的是NSOrderedSet。这将强制执行零重复,并将维护一个订单 - 这意味着您可以对其进行排序,它的功能与NSArray类似。

当然,您需要NSMutableOrderedSet进行就地排序。这是文档的链接 https://developer.apple.com/library//ios/documentation/Foundation/Reference/NSMutableOrderedSet_Class/index.html#//apple_ref/swift/cl/c:objc(cs)NSMutableOrderedSet

编辑:您需要的只是实现- (void)sortUsingComparator:(NSComparator)cmptr并给它一个确定顺序的方法。

答案 1 :(得分:1)

您建议的解决方案没问题,但您可以使用其中一种内置排序方法而不是自己迭代字典,并使用字典中的计数来决定排序结果。如果您的功能提供的两个项目的计数匹配,那么您可以应用您的二级排序逻辑。

答案 2 :(得分:1)

好的,这是我解决这个问题的解决方案:

-(NSMutableArray *)sortByFreq : (NSArray *)inArray {

    //first calculate counts
    NSMutableDictionary *d = [NSMutableDictionary new];
    for (NSString *s in inArray) {
        if (![d objectForKey:s]) {
            [d setValue:[NSNumber numberWithInt:1] forKey:s];
        }else{
            [d setValue:[NSNumber numberWithInt:[[d objectForKey:s] intValue]+1] forKey:s];
        }
    }

    //create help array with keys to sort
    NSMutableDictionary *d2 = [NSMutableDictionary new];
    for (NSString *key in d) {
        [d2 setValue:key forKey:[NSString stringWithFormat:@"%@_%@", [d objectForKey:key], key]];
    }

    //sort keys
    NSArray *sortedArray = [[d2 allKeys] sortedArrayUsingComparator:
                            ^NSComparisonResult(id obj1, id obj2){
                                NSArray *a1 = [obj1 componentsSeparatedByString:@"_"];
                                NSArray *a2 = [obj2 componentsSeparatedByString:@"_"];

                                //compare
                                if ([[a1 objectAtIndex:0] isEqualToString:[a2 objectAtIndex:0]]) {
                                    return [[a1 objectAtIndex:1] compare:[a2 objectAtIndex:1]];
                                }
                                return [obj2 compare:obj1];
                            }];

    //create array to output
    NSMutableArray *outputArray = [NSMutableArray new];
    for (NSString *key in sortedArray) {
        [outputArray addObject:[d2 objectForKey:key]];
    }

    return outputArray;
}

我希望这有帮助。

您可以这样称呼它:

NSLog(@"%@", [self sortByFreq:[[NSArray alloc] initWithObjects:@"c", @"a", @"b", @"c", @"b", nil]]);
NSLog(@"%@", [self sortByFreq:[[NSArray alloc] initWithObjects:@"c", @"c", @"c", @"a", @"b", nil]]);
NSLog(@"%@", [self sortByFreq:[[NSArray alloc] initWithObjects:@"b", @"a", @"a", @"a", @"c", nil]]);
NSLog(@"%@", [self sortByFreq:[[NSArray alloc] initWithObjects:@"c", @"c", @"b", @"b", @"a", nil]]);

输出将是:

(b,c,a)

(c,a,b)

(a,b,c)

(b,c,a)