Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add elements of two array with each other

Tags:

ios

swift

swift3

I have 2 Array of type Int like this

let arrayFirst = [1,2,7,9]
let arraySecond = [4,5,17,20]

I want to add the elements of each array, like arrayFirst[0] + arraySecond[0], arrayFirst[1] + arraySecond[1] an so on and assign it to another array, so the result of the array would be like

[5, 7, 24, 29]

What would be the best practice to achieve this using swift3

like image 357
Nishchal Sharma Avatar asked Nov 11 '16 06:11

Nishchal Sharma


People also ask

How do you sum two array elements?

The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum.

How do you add two arrays to each other?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

Can we add two arrays?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.


1 Answers

You can add both the arrays like this

let arrayFirst = [1,2,7,9]
let arraySecond = [4,5,17,20]

let result = zip(arrayFirst, arraySecond).map(+)
print(result)
like image 179
Rajat Avatar answered Oct 08 '22 11:10

Rajat