I have 2 arrays say arrayA
& arrayB
. arrayA
has the elements say [1,2] and arrayB
has the elements say [3,4]. Now I want to multiply and add the elements in these arrays like so.. 1x3 + 2x4 = 11. How can I achieve this...?
答案 0 :(得分:6)
Here a combo of zip, map and reduce:
let result = (zip([1,2], [3,4]).map { $0.0 * $0.1 }).reduce(0, +)
print(result) // 11
(1,3), (2,4)
map
I am iterating for each element of the array producing at each iteration a new element$0
means the element of the sequence at the current iteration. Since the element is a pair (because of zip), we can access to the first sub-element of the pair with $0.0 and to the second with $0.1.map
) we get an array of products, just need to "reduce" it to a number, summing all the resulting elements with reduce
.reduce
starts from 0
as initial value, then with the abbreviation +
we can accumulate the sums of all the elements.答案 1 :(得分:2)
请注意,您可以直接对压缩序列应用REL
操作,而不是使用链式map
和reduce
(分别用于乘法和求和),并修改{ {1}}闭包以相应地计算压缩序列中成对乘法对象的总和:
reduce
答案 2 :(得分:1)
Try this.
let A = [1,2]
let B = [3,4]
let C = zip(A, B).map {$0.0 * $0.1}
print(C) // [3, 8]
let sum = C.reduce(0, +)
print(sum)//11