我们说我有一个像这样的多维数组:
(
(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)
任何帮助将不胜感激!
答案 0 :(得分:3)
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);
答案 1 :(得分:2)
这样的事情应该起作用
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答案 2 :(得分:1)
你可以用键值编码来做到这一点:
NSArray *array = …; // Whatever you have
NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"@sum.self" ascending:NO]; // @sum is an aggregate
NSArray *sorted = [array sortedArrayUsingDescriptors:@[sorter]]);