如何使用高阶函数获得对角线的总和? [英] How to get the summation of diagonal lines using higher-order functions?
本文介绍了如何使用高阶函数获得对角线的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下2D数组:
let array = [
[11, 2, 4],
[4, 5, 6],
[10, 8, -12]
]
我想要得到的是对角线的总和:
What I want to get is the summation of the diagonals:
- 作为
firstDiagnal
:11 + 5 +(-12)= 4 - 作为
secondDiagnal
:4 + 5 + 10 = 19
- As
firstDiagnal
: 11 + 5 + (-12) = 4 - As
secondDiagnal
: 4 + 5 + 10 = 19
我可以使用标准的 for-in
循环来实现它: / p>
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)
但是,可以如果我们尝试使用高阶函数?例如 map
和 reduce
?
However, what could it be if we tried to use higher-order functions? such as map
and reduce
?
推荐答案
要获得第一个和,您需要第i行的第i个元素:
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, +)
这篇关于如何使用高阶函数获得对角线的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文