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

后端 未结 2 993
时光说笑
时光说笑 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:56

    To begin with, you can write a neat extension to get the diagonal out of a nested array:

    extension Array {
    
        func diagonal(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, +)
    

提交回复
热议问题