Sum two arrays element-by-element in Java
One more answer, using streams and providing a more generic solution:
import org.junit.Assert;
import org.junit.Test;
import java.util.function.IntBinaryOperator;
import java.util.stream.IntStream;
public class SOTest {
@Test
public void test() {
int[] a = {0, 1, 2};
int[] b = {3, 4, 5};
int[] sum = applyOn2Arrays((x, y) -> x + y, a, b);
int[] diff = applyOn2Arrays((x, y) -> x - y, a, b);
int[] mult = applyOn2Arrays((x, y) -> x * y, a, b);
Assert.assertArrayEquals(new int [] {3,5,7}, sum);
Assert.assertArrayEquals(new int [] {-3,-3,-3}, diff);
Assert.assertArrayEquals(new int [] {0,4,10}, mult);
}
private int[] applyOn2Arrays(IntBinaryOperator operator, int[] a, int b[]) {
return IntStream.range(0, a.length)
.map(index -> operator.applyAsInt(a[index], b[index]))
.toArray();
}
}
There's certainly nothing to enable this in the language. I don't know of anything in the standard libraries either, but it's trivial to put the code you've written into a utility method which you can call from anywhere you need it.
check this one: used sum and carry
public class SumOfTwoArrays{
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2){
int na = arr1.length;
int nb = arr2.length;
int nc;
int min;
if(na > nb){
nc = na + 1;
min = nb;
}else{
nc = nb + 1;
min = na;
}
int[] c = new int[nc];
int sum = 0;
int carry = 0;
int i = na - 1;
int j = nb - 1;
int k = nc - 1;
while(i >= 0 && j>=0){
sum = arr1[i] + arr2[j] + carry;
i--;
j--;
c[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
k--;
}//end of while loop
while(i >= 0){ //n2 has exhausted
sum = arr1[i] + carry;
c[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
i--;
k--;
}
while(j >= 0){ //n1 has exhausted
sum = arr2[j] + carry;
c[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
k--;
j--;
}
c[k] = carry;
return c;
}
}
Input: arr1 = {2, 1, 3}; arr2 = {3, 2};
Output: c: {0, 2, 4 ,5}