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.
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.
S = sum( A ) returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With