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

后端 未结 2 997
时光说笑
时光说笑 2021-01-17 22:25

Consider the following 2D array:

let array = [
                [11, 2, 4],
                [4, 5, 6],
                [10, 8, -12]
            ]
2条回答
  •  遥遥无期
    2021-01-17 22:39

    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, +)
    

提交回复
热议问题