ios 如何用Swift求矩阵对角线的加法?

68bkxrlz  于 2023-02-06  发布在  iOS
关注(0)|答案(2)|浏览(116)

我想得到从左到右和从右到左的对角线的加法。请分享一下我们是如何一步步解决这些问题的。我对此一无所知。请看附件。

先谢了。

7cwmlq89

7cwmlq891#

var sumLeftToRight: Int = 0
var sumRightToLeft: Int = 0
var arr: [[Int]] = []

for i in 0..<arr.count {
   sumLeftToRight += arr[i][i]
   sumRightToLeft += arr[i][arr.count-i-1]
}
5lhxktic

5lhxktic2#

//Swift 5 Solution within a function with a bit different approach in case negative numbers in test-cases 
func sumDiagonally(arr:[[Int]])-> Int{
    var subn = 0
    var sum1st = 0
    var sum2nd = 0
    for i in 0..<arr.count{
        sum1st += arr[i][i]
        sum2nd += arr[i][arr.count-i-1]
        subn = sum1st - sum2nd
            if sum1st < sum2nd{
            subn = subn * -1
            }
        }
    return subn
}
sumDiagonally(arr: [[1,2,3],
                    [4,5,6],
                    [9,8,9]])

相关问题