Multiply and add elements in 2 arrays

时间:2018-02-03 09:58:05

标签: ios swift

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...?

3 个答案:

答案 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. Zip makes a sequence of pairs based on the two arrays: (1,3), (2,4)
  2. with map I am iterating for each element of the array producing at each iteration a new element
  3. $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.
  4. finally (after map) we get an array of products, just need to "reduce" it to a number, summing all the resulting elements with reduce.
  5. (0, +) means that reduce starts from 0 as initial value, then with the abbreviation + we can accumulate the sums of all the elements.

答案 1 :(得分:2)

请注意,您可以直接对压缩序列应用REL操作,而不是使用链式mapreduce(分别用于乘法和求和),并修改{ {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