15

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

我知道您可以使用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 类,但该方法相当冗长。

4

8 回答 8

13

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.

于 2013-09-04T15:55:14.793 回答
4

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

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();
    }
}
于 2018-10-03T08:57:45.613 回答
2

检查这个:使用总和和进位

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}

于 2017-07-01T02:58:10.573 回答
1

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

不,这并不容易,因为您不能覆盖 java 中的运算符。

您可以使用支持add的javax.vecmath.Vector3d(正如@crush 在另一条评论中所说的 [credits to him]),但这只不过是添加值:

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

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

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

于 2013-09-04T15:59:42.047 回答
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(" ")));
   }
}
于 2018-10-03T07:29:36.120 回答
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");
    }
}

}
于 2020-04-30T22:51:41.520 回答
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");

        }

    }

}
于 2020-04-30T22:56:32.190 回答
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();
}
于 2019-03-28T12:45:30.877 回答