Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the summation of diagonal lines using higher-order functions?

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:

  • As firstDiagnal: 11 + 5 + (-12) = 4
  • As secondDiagnal: 4 + 5 + 10 = 19

I 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?

like image 260
Ahmad F Avatar asked Oct 04 '18 12:10

Ahmad F


1 Answers

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, +)
like image 196
Rob Napier Avatar answered Nov 15 '22 01:11

Rob Napier