根据 objective c 中的内部数组之和对多维数组进行排序

Sort multi dimensional array based on sum of internal arrays in objective c

假设我有一个这样的多维数组:

(
    (2, 2, 1),
    (0, 1, 2),
    (0, 1, 1),
    (0, 0, 1),
    (0, 0, 2),
    (0, 1, 3),
    (0, 1, 0),
    (0, 0, 1),
    (0, 0, 1),
    (1, 3, 3)
)

现在我需要按照内部数组总和的降序对这个数组进行排序。

我尝试在字典中添加这个数组和另一个数组的总和值,但如果总和包含相似的数字,它就不起作用。

即,我希望结果为:

(1, 3, 3),
(2, 2, 1),
(0, 1, 3),
(0, 1, 2),
(0, 1, 1),
(0, 0, 2),
(0, 0, 1),
(0, 0, 1),
(0, 1, 0)

如有任何帮助,我们将不胜感激!

像这样的东西应该可以工作

let multiDimenArray = [[0,1,2],[2,3,4],[1,2,3]]

let sorted = multiDimenArray.sort { a, b -> Bool in

    let aR = a.reduce(0, combine:+) //sums the numbers inside a
    let bR = b.reduce(0, combine:+)

    return aR > bR //swap direction of > if you want ascending or descending
}

print(sorted);

打印

[[2, 3, 4], [1, 2, 3], [0, 1, 2]]

编辑:

doh,大脑忘记了它应该在 objective-c

Fonix 的答案很酷,但它是 Swift,在 Obj-C 中,然后这样做:

NSArray *numArray = @[@[@1,@1,@1], @[@0,@0,@0], @[@2,@2,@2], @[@0,@1,@2]];

NSArray *sortedArray;
sortedArray = [numArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSNumber *first = [(NSArray *)a valueForKeyPath:@"@sum.self"];
        NSNumber *second = [(NSArray *)b valueForKeyPath:@"@sum.self"];
        return [first compare:second];
    }];

NSLog(@"sorted %@",sortedArray);

您可以使用键值编码来做到这一点:

NSArray *array = …; // Whatever you have

NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"@sum.self" ascending:NO]; // @sum is an aggregate
NSArray *sorted = [array sortedArrayUsingDescriptors:@[sorter]]);