1

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.

i.e, 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!

Antti29
  • 2,953
  • 12
  • 34
  • 36
Rajesh S
  • 133
  • 1
  • 9

3 Answers3

3

Fonix's answer is cool, but it's Swift, In Obj-C then do like this:

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);
Tj3n
  • 9,837
  • 2
  • 24
  • 35
2

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

Fonix
  • 11,447
  • 3
  • 45
  • 74
  • Worth noting you can just pass the `+` operator into the `combine:` argument of `reduce`, as Swift treats it as a function. – Hamish Mar 29 '16 at 08:01
1

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]]);
Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50