在 Java 中逐个元素地求和两个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18618487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:34:40  来源:igfitidea点击:

Sum two arrays element-by-element in Java

javaarrays

提问by I Like to Code

What is the easiest way to sum two arrays element-by-element?

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

I know that you can use a forloop such as the following:

我知道您可以使用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];
}

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?

但在 MATLAB 等语言中,您只需编写c = a + b. 有没有一种简单的方法可以在 Java 中做到这一点?

The method that comes to mind is using the RealVector class from Apache Commons Math, but that method is rather verbose.

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

采纳答案by Jon Skeet

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.

语言中肯定没有什么可以启用它。我也不知道标准库中的任何内容,但是将您编写的代码放入一个实用程序方法中是微不足道的,您可以从任何需要它的地方调用它。

回答by Philipp Sander

c = a + bIs there an easy way to do this in Java?

c = a + b有没有一种简单的方法可以在 Java 中做到这一点?

No. not this easy, because you can not override operators in java.

不,没那么容易,因为你不能在 java 中覆盖运算符。

You could use javax.vecmath.Vector3d(as @crush said it in another comment [credits to him]) which supports addbut this does nothing more than adding the values:

你可以使用javax.vecmath.Vector3d(如@crush说,它在另一个评论[学分他])支持,但是这并没有超过增加值:

/**
  * 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 JSciencewhich has a mathematical-Vektor

或使用具有数学Vektor 的库,例如JScience

But if you want a performant way: your solution is the best you can get in my opinion!

但是,如果您想要一种高性能的方式:在我看来,您的解决方案是最好的!

回答by Abhishek Dhiman

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

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

Output: c: {0, 2, 4 ,5}

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

回答by Jai Prakash

With Java 8 Streams it's very easy to do this. And this method is very efficient when adding a large array size.

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

回答by Benoit

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

回答by Yash

Addition of array value with their number like 21+9 = 30. when 9+1=10tens place value get borrowed and added to tens place. Where form java 8 the result is 21+9 = 210.

将数组值与其编号相加,如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]


Simple java logic to all two arrays values into single array:

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

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:

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

回答by lachhabayoub

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

}

回答by lachhabayoub

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

        }

    }

}