在Java中按元素求和两个数组

时间:2013-09-04 15:53:04

标签: java arrays

逐个元素对两个数组求和的最简单方法是什么?

我知道您可以使用for循环,如下所示:

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];
}

但是在MATLAB等语言中,只需编写c = a + b就可以完成逐个元素的数组求和。在Java中有一种简单的方法吗?

我想到的方法是使用Apache Commons Math中的RealVector类,但该方法相当冗长。

8 个答案:

答案 0 :(得分:12)

语言中肯定无法启用此功能。我也不知道标准库中的任何内容,但是将您编写的代码放入实用程序方法中是非常简单的,您可以从任何需要它的地方调用它。

答案 1 :(得分:2)

使用流并提供更通用的解决方案的另一个答案:

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();
    }
}

答案 2 :(得分:1)

  

c = a + b在Java中有一种简单的方法吗?

没有。这不容易,因为你无法覆盖java中的运算符。

您可以使用javax.vecmath.Vector3d(正如@crush在另一条评论中所说的那样[对他而言])支持add,但这只会添加值:

/**
  * 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;
}

你这样使用它:

vectorC = vectorA.copy().add(vectorB);
//you need to copy the vectorA because add manipulates the object your calling it on

或使用具有数学的JScience等库{ - 3}}

但如果你想要一个高效的方式:你的解决方案是我认为最好的解决方案!

答案 3 :(得分:0)

使用Java 8 Streams可以很容易地做到这一点。而且在添加大数组大小时此方法非常有效。

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(" ")));
   }
}

答案 4 :(得分:0)

添加数组值及其数字,例如21+9 = 30。当9+1=10十位值被借用并添加到十位时。 在Java 8形式中,结果为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]

将所有两个数组的值转换为单个数组的简单java逻辑:

  

注意:第一个数组的长度必须大于第二个数组的长度。

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;
}

使用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();
}

答案 5 :(得分:0)

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");
    }
}

}

答案 6 :(得分:0)

使用代码

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");

        }

    }

}

答案 7 :(得分:-1)

检查一下:使用sum并携带

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;
    }
}

输入: arr1 = {2,1,3}; arr2 = {3,2};

输出: c:{0,2,4,5}