Reputation: 7251
What is the easiest way to sum two arrays element-by-element?
I know that you can use a for
loop such as the following:
int[] a = {0, 1, 2};
int[] b = {3, 4, 5};
int[] c = new int[a.length];
for (int i = 0; i < a.length; ++i) {
c[i] = a[i] + b[i];
}
But in languages such as MATLAB, you can do the element-by-element array sum by just writing c = a + b
. Is there an easy way to do this in Java?
The method that comes to mind is using the RealVector class from Apache Commons Math, but that method is rather verbose.
Upvotes: 15
Views: 87924
Reputation: 1
public class Test{
public static void main(String[] args) {
int a[] = {12, 13, 14, 44};
int b[] = {11, 10, 15, 20, 50};
int[] cs = new int[a.length];
System.out.println("----------------------FIRST TABLE--------------------------------");
for (int i : a) {
System.out.println("Element : " + i);
}
System.out.println("----------------------SECOND TABLE -----------------------------");
for (int j : b) {
System.out.println("Element : " + j);
}
System.out.println("-----------------------SUM OF TABLE------------------------------------");
if (a.length == b.length) {
for (int i = 0, j = 0, k = 0; i < a.length; i++, j++, k++) {
cs[k] = a[i] + b[j];
}
} else {
System.out.println("Arrays have different length");
}
}
}
Upvotes: 0
Reputation: 1
Using your code
public class Test{
public static void main(String[] args){
int[] a = {0, 1, 2};
int[] b = {3, 4, 5};
int[] c = new int[a.length];
if(a.length==b.length) {
for (int i = 0 ,j=0,k=0; i < a.length; i++,j++,k++) {
c[k] = a[i] + b[j];
System.out.println(c[k]);
}}
else {
System.out.println("Should be same length in two arrays");
}
}
}
Upvotes: 0
Reputation: 9568
Addition of array value with their number like 21+9 = 30
. when 9+1=10
tens place value get borrowed and added to tens place.
Where form java 8 the result is 21+9 = 210
.
Array 1 + Array 2 = Reslut Array ~ Java8 Result
{0, 1, 2} + {3, 4, 9} = [0, 3, 6, 1] ~ [3, 5, 11]
{0, 1, 2, 1} + {3, 4, 9} = [0, 0, 4, 7, 0] ~ [3, 5, 11, 1]
Simple java logic to all two arrays values into single array:
NOTE: First array's length must be greater than Second array's length.
public static int[] arraysAddition_Int(int[] a1, int[] a2) {
int borrowing = 0;
int[] resultArr = new int[a1.length+1];
for (int i = a1.length - 1, j = a2.length - 1; i >= 0; i--, j--) {
int n1 = a1[i];
int n2 = 0;
if (j >= 0) {
n2 = a2[j];
}
int temp = n1 + n2 + borrowing;
borrowing = 0; // After adding make it as ZERO.
if (temp > 9) {
borrowing = 1;
temp -= 10;
}
resultArr[i+1] = temp;
}
if (borrowing > 0) {
resultArr[0] = borrowing;
}
System.out.format("[%s + %s]=[%s]\n --- \n",
Arrays.toString(a1), Arrays.toString(a2), Arrays.toString(resultArr));
return resultArr;
}
Using Java 8:
private static int[] arraysAddition_java8(int[] a, int b[]) {
int startInclusive = 0, endExclusive = Math.max(a.length, b.length);
IntUnaryOperator mapper = index -> (index < a.length ? a[index] : 0) + (index < b.length ? b[index] : 0);
return IntStream.range(startInclusive, endExclusive).map(mapper).toArray();
}
Upvotes: 0
Reputation: 5394
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();
}
}
Upvotes: 5
Reputation: 11
With Java 8 Streams it's very easy to do this. And this method is very efficient when adding a large array size.
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner scan = new Scanner(System.in);
Integer arrSize = scan.nextInt();
Integer firstArr[] = new Integer[arrSize];
Integer secArr[] = new Integer[arrSize];
Integer sumArr[] = new Integer[arrSize];
for(int i = 0; i < arrSize; i++) firstArr[i] = scan.nextInt();
for(int i = 0; i < arrSize; i++) secArr[i] = scan.nextInt();
IntStream.range(0, arrSize).forEach(i -> sumArr[i] = firstArr[i] + secArr[i]);
System.out.println(Arrays.asList(sumArr).stream().map(n->n.toString()).collect(Collectors.joining(" ")));
}
}
Upvotes: 0
Reputation: 41
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}
Upvotes: 2
Reputation: 10249
c = a + b
Is there an easy way to do this in Java?
No. not this easy, because you can not override operators in java.
You could use javax.vecmath.Vector3d (as @crush said it in another comment [credits to him]) which supports add but this does nothing more than adding the values:
/**
* Sets the value of this tuple to the vector sum of itself and tuple t1.
* @param t1 the other tuple
*/
public final void add(Tuple3d t1) {
x += t1.x;
y += t1.y;
z += t1.z;
}
you use it like this:
vectorC = vectorA.copy().add(vectorB);
//you need to copy the vectorA because add manipulates the object your calling it on
or Use library such as JScience which has a mathematical-Vektor
But if you want a performant way: your solution is the best you can get in my opinion!
Upvotes: 1
Reputation: 1500135
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.
Upvotes: 13