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

自古美人都是妖i 提交于 2019-12-01 17:03:41

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, +)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!