Consider the following 2D array:
let array = [
[11, 2, 4],
[4, 5, 6],
[10, 8, -12]
]
What I want to get is the summation of the diagonals:
firstDiagnal
: 11 + 5 + (-12) = 4secondDiagnal
: 4 + 5 + 10 = 19I could achieve it using a standard for-in
loop:
var firstDiagnal = 0
var secondDiagnal = 0
for i in 0..<array.count {
firstDiagnal += array[i][i]
secondDiagnal += array[i][array[i].count - 1 - i]
}
print(firstDiagnal)
print(secondDiagnal)
However, what could it be if we tried to use higher-order functions? such as map
and reduce
?
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, +)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With