简体   繁体   English

根据目标c中内部数组的总和对多维数组进行排序

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

Let's say I have a multi-dimensional array like this: 假设我有一个像这样的多维数组:

(
    (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)
)

Now I need to sort this array in descending order of the internal array's sum. 现在,我需要按照内部数组总和的降序对数组进行排序。

I tried by adding this array and another array of the sum values in a dictionary, but it doesn't work if the sum contains similar numbers. 我尝试通过在字典中添加此数组和总和值的另一个数组,但是如果总和包含相似的数字,它将不起作用。

ie, I want the result to be: 即,我希望结果是:

(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)

Any help would be appreciated! 任何帮助,将不胜感激!

Fonix's answer is cool, but it's Swift, In Obj-C then do like this: 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);

something like this should work 这样的事情应该工作

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);

prints 版画

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

edit: 编辑:

doh, brain forgot that it should be in objective-c Doh,大脑忘记了它应该在Objective-C中

You can do that with key-value coding: 您可以使用键值编码做到这一点:

NSArray *array = …; // Whatever you have

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM