Reputation:
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...?
Upvotes: 1
Views: 1447
Reputation: 10105
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.Upvotes: 9
Reputation: 73176
Note that rather than using a chained map
and reduce
(for multiplication and summation, respectively), you could directly apply the reduce
operation on the zipped sequence, and modify the reduce
closure to accordingly calculate the sum of the pair-wise multiplied objects in the zipped sequence:
let a = [1, 2]
let b = [3, 4]
let result = zip(a,b).reduce(0) { $0 + $1.0 * $1.1 } // 11
Upvotes: 2
Reputation: 481
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
Upvotes: 0