Consider the following 2D array:
let array = [
[11, 2, 4],
[4, 5, 6],
[10, 8, -12]
]
To get the first sum, you want the i'th element of the i'th row:
let firstDiag = array.enumerated().map { $1[$0] }.reduce(0, +)
To get the second sum, you want the same thing, but the columns reversed:
let secondDiag = array.enumerated().map { $1.reversed()[$0] }.reduce(0, +)
To begin with, you can write a neat extension to get the diagonal out of a nested array:
extension Array {
func diagonal<T>(order: Int) -> [T] where Element == [T] {
var order = order
return self.compactMap {
guard order >= 0, $0.count > order else {
order -= 1
return nil
}
let output = $0[order]
order -= 1
return output
}
}
}
let array = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(array.diagonal(order: 0)) // [1]
print(array.diagonal(order: 1)) // [2, 4]
print(array.diagonal(order: 2)) // [3, 5 ,7]
print(array.diagonal(order: 3)) // [6, 8]
It's then just simply a case of the bog-standard reduce and sum:
let fristDiagonal = array.diagonal(order: 0).reduce(0, +)
let secondDiagonal = array.diagonal(order: 1).reduce(0, +)