Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding/summing two arrays

Tags:

c#

linq

I've encountered a purely hypothetical problem which feels like it has an easy solution if I find the right linq method...

I have two arrays of ints and I know they are the same size. I want to create a third array of the same size where the elements in the third array are the sum of the elements in the first two arrays in the corresponding position.

Below is a method that should show what I want to do.

public static int[] AddArrays(int[] a, int[] b) {     int[] newArray = new int[a.Length];     for (int i = 0; i<a.Length; i++)     {         newArray[i]=a[i]+b[i];     }     return newArray; } 

Are there any Linq methods that I can just use like

return a.DoStuff(b, (x,y) => x+y) 

or something like that?

I should note that this probably falls in the category of homework since the original problem came from a website I was looking at (though I can't find a direct link to the problem) and not as a question I need for work or anything.

If no simple method exists then what is the most Linqy way to do this? an array.each would seem to have the problem of not being able to index the second array easily to add the values to the one you are iterating through leading me to wonder if Linq would be any help at all in that situation...

like image 716
Chris Avatar asked Sep 09 '11 09:09

Chris


People also ask

How do you sum two arrays?

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 sum two arrays in Python?

To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are​ not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.

How do you add two arrays in C++?

If you're trying to add the values of two array elements and store them in an array, the syntax is as simple as: But this assumes that the arrays have been declared and arr2 and arr3 have been initialized. and fifth you are printing the result before you're done computing it.


2 Answers

Zip it :)

var a = new int[] {1,2,3 }; var b = new int[] {4,5,6 }; a.Zip(b, (x, y) => x + y) 
like image 160
Ankur Avatar answered Sep 22 '22 07:09

Ankur


You can use the Select method.

int[] a = new[] { 1, 2, 3 }; int[] b = new[] { 10, 20, 30 };  var c = a.Select ((x, index) => x + b[index]).ToArray(); 
like image 20
Tom Brothers Avatar answered Sep 19 '22 07:09

Tom Brothers