简体   繁体   English

如何添加两个不同大小的数组?

[英]How to add two different sized arrays?

If I have an array int[] a = new int[]{1, 2, 3};如果我有一个数组int[] a = new int[]{1, 2, 3}; and another int[] b = new int[]{3, 2};另一个int[] b = new int[]{3, 2}; and I want to add the two together, I would do:我想将两者加在一起,我会这样做:

if (a.length >= b.length){
    int[] c = new int[a.length];

    for(int i=0; i<c.length; i++){
        c[i] = a[i] + b[i];
        return c;
    }
}
else{
    int[]c = new int[b.length];

    for(int i=0; i<c.length; i++){
        c[i] = a[i] + b[i];
        return c;
    }

But when I print c, I get {4, 4} and the 3 on the end is left out, where am I going wrong?但是当我打印 c 时,我得到 {4, 4} 并且最后的 3 被遗漏了,我哪里出错了?

Thanks in advance for any help!在此先感谢您的帮助!

public Poly add(Poly a){

    if (coefficients.length <= a.coefficients.length){
        int[] c = new int[coefficients.length]; 

        for (int i=0; i<added.length; i++){
            c[i] = a.coefficients[i] + coefficients[i];
        }

        Poly total = new Poly(c);
        return total;
    }
    else{
        int[] added = new int[a.coefficients.length];

        for (int i=0; i<added.length; i++){
            added[i] = a.coefficients[i] + coefficients[i];
        }

        Poly total = new Poly(c);
        return total;
    }       
}

and Poly is a constructor that takes an int array as an argument ( Poly ex = new Poly(new int[]{1, 2, 3}) )而 Poly 是一个以 int 数组作为参数的构造函数( Poly ex = new Poly(new int[]{1, 2, 3})

You can define a destination array with a length of the max of both source arrays. 您可以定义一个目标数组,其长度为两个源数组的最大值。 After that you just do array bounds-checking. 之后,您只需要进行数组边界检查即可。 Of course, you should also add checks for null before you even begin to loop over c . 当然,在开始循环c之前,还应该添加null检查。

import java.util.Arrays;

class AddArrays {
    private static int[] a = new int[] { 1, 2, 3 };
    private static int[] b = new int[] { 3, 2 };
    private static int[] c = add(a, b);

    private static int[] add(int[] a, int[] b) {
        int[] c = new int[(int) Math.max(a.length, b.length)];
        for (int i = 0; i < c.length; i++) {
            if (a.length > i) {
                c[i] += a[i];
            }
            if (b.length > i) {
                c[i] += b[i];
            }
        }
        return c;
    }

    public static void main (String[] args) {
        System.out.println(Arrays.toString(c));
    }
}

Output: 输出:

[4, 4, 3]
int[] vector1={1,2,3,4};
int[] vector2={1,2,3};
int result[]=new int[(int)Math.max(vector1.length,vector2.length)];
for(int i=0;i<result.length; i++) {
    if(vector1.length>i && vector2.length>i) 
        result[i]=vector1[i] + vector2[i];

    else if(vector1.length<vector2.length)
        result[i]+=vector2[i];

    else if(vector2.length<vector1.length) 
        result[i]+=vector1[i];

    System.out.print(result[i]+"    ");
}

Here, first arraysize of the result is first predicted by comparing the sizes of two input arrays and setting the maximum size from comparison of two. 在此,首先通过比较两个输入数组的大小并通过比较两个数组来设置最大大小来预测结果的第一数组大小。

Next, the input array which is larger than the other is just added to the result array by comparing the sizes of the input arrays inside the for loop. 接下来,通过比较for循环内输入数组的大小,将比另一个数组大的输入数组添加到结果数组。

Result: 结果:

2    4    6    4

Firstly, you'll get a ArrayIndexOutOfBoundsException because on the last iteration (3rd iteration): c[2] = a[2] + b[2] , b[2] is out of bound since it is smaller. 首先,您将获得ArrayIndexOutOfBoundsException,因为在最后一次迭代(第3次迭代)中: c[2] = a[2] + b[2] ,因为b[2]较小,所以超出范围。 So you can't check null in this case you have to check the length of the shorter array. 因此,在这种情况下,您不能检查null,而必须检查较短数组的长度。

Also I'm not sure how you get {4, 4} because I need more code to understand what is going on. 另外,我不确定您如何获得{4,4},因为我需要更多代码来了解发生了什么。

But anyway here's a solution to avoid ArrayIndexOutOfBoundsException: 但是无论如何,这是避免ArrayIndexOutOfBoundsException的解决方案:

public static int[] add(int[] a, int[] b) {
    int[] c;

    if (a.length >= b.length){
        c = new int[a.length];

        for(int i=0; i<c.length; i++){
            c[i] = (i < b.length) ? a[i] + b[i]: a[i];
        }
    }
    else{
        c = new int[b.length];

        for(int i=0; i<c.length; i++){
            c[i] = (i < a.length) ? a[i] + b[i]: b[i];
        }
    }
    return c;
}

You've gone out of bounds because program is looking for number on the third place in the "a" and "b" array. 您已经超出范围,因为程序正在寻找“ a”和“ b”数组中第三位的数字。 In the "a" array it's number 3, but array "b" has no such number so you get an error index out of bounds. 在“ a”数组中,它是数字3,但是数组“ b”没有这样的数字,因此您将获得一个错误索引。 I fixed that problem by doing the next thing: 我通过做下一件事来解决该问题:

if (a.length >= b.length){
    int[] c = new int[a.length];

    for(int i=0; i < c.length; i++){
        if (i < b.length)
            c[i] = a[i] + b[i];
        else
            c[i] = a[i];
    }

    return c;

} else {
    int[]c = new int[b.length];

    for(int i=0; i<c.length; i++){
        if (i < a.length)
            c[i] = a[i] + b[i];
        else
            c[i] = b[i];
    }

    return c;

}

New array gets the sum of numbers while both arrays got numbers on that index and when the shorter array is out of number the rest of numbers are simply copied into the new array. 新数组获取数字的总和,而两个数组都在该索引上获取数字,而当较短的数组缺少数字时,其余数字将简单地复制到新数组中。 Hope it helps, if you have any other questions please let me know. 希望对您有所帮助,如果还有其他问题,请告诉我。

You've got a couple problems, namely: 您遇到了几个问题,即:

  • Your lengths are mixed up so you'll get an exception. 您的长度混合在一起,所以您会遇到例外。 You should do the addition for the smaller array's length, then copy the rest of the larger array. 您应该对较小数组的长度进行加法运算,然后复制其余较大数组的长度。 (Assuming that is the desired behavior.) (假定这是所需的行为。)
  • In the first example, you have your return statements inside your loops. 在第一个示例中,您将return语句放入循环中。 Move them to outside. 将它们移到外面。

If it were me, what I would do is assume one was the longer array and swap the references if it's not. 如果是我,我会做的是假设其中一个是较长的数组,如果不是,则交换引用。 This way you only have to write one loop. 这样,您只需要编写一个循环。

static int[] sum(int[] a, int[] b) {
    int[] c;

    if(b.length > a.length) {
        c = a;
        a = b;
        b = c;
    }

    c = Arrays.copyOf(a, a.length);

    for(int i = 0; i < b.length; i++) {
        c[i] += b[i];
    }

    return c;
}

Instead of copyOf , the other way you could do it is something like this: 代替copyOf ,另一种方法是这样的:

    ...

    c = new int[a.length];

    int i = 0;
    for(; i < b.length; i++) {
        c[i] = a[i] + b[i];
    }
    for(; i < a.length; i++) {
        c[i] = a[i];
    }

    return c;
}

Or instead of the second loop: 或者代替第二个循环:

    System.arraycopy(a, i, c, i, a.length - i);

I think either of those are more clear than the alternative, which would be to put an if statement inside the loop: 我认为其中任何一个都比替代方案更明确,替代方案是将if语句放入循环中:

    for(int i = 0; i < c.length; i++) {
        if(i < b.length) {
            c[i] = a[i] + b[i];
        } else {
            c[i] = a[i];
        }
    }

Doing that is also another branch which will technically be a little slower. 这样做也是另一个分支,从技术上讲它将稍微慢一些。

Here is a testdriven approach to solve the problem.Build your boundary cases and start writing the code.You should be able to solve this problem. 这是一种测试驱动的方法来解决问题,构建边界案例并开始编写代码,您应该能够解决此问题。

package loopfusion;

import java.util.Arrays; 导入java.util.Arrays;

public class AddArray { 公共类AddArray {

public static void main(String[] args) {
    //second array is bigger
    int[] array1 = {1, 3, 4, 5, 7};
    int[] array2 = {4, 45, 54, 65, 34, 45, 234, 56};
    int[] resultArr = add(array1, array2);
    for (int i = 0; i < resultArr.length; i++) {
        System.out.println(resultArr[i]);
    }
    //first array is bigger
    int[] array3 = {4, 45, 54, 65, 34, 45, 234, 56};
    int[] array4 = {1, 3, 4, 5, 7};
    resultArr = add(array3, array4);
    for (int i = 0; i < resultArr.length; i++) {
        System.out.println(resultArr[i]);
    }

    //first array is empty
    int[] array5 = {};
    int[] array6 = {1, 3, 4, 5, 7};
    resultArr = add(array5, array6);
    for (int i = 0; i < resultArr.length; i++) {
        System.out.println(resultArr[i]);
    }

    //Second array is empty
    int[] array7 = {1, 3, 4, 5, 7};
    int[] array8 = {};
    resultArr = add(array7, array8);
    for (int i = 0; i < resultArr.length; i++) {
        System.out.println(resultArr[i]);
    }

    //Both arrays are empty
    int[] array9 = {};
    int[] array10 = {};
    resultArr = add(array9, array10);
    for (int i = 0; i < resultArr.length; i++) {
        System.out.println(resultArr[i]);
    }

    //Both arrays are of equal length
    int[] array11 = {1, 3, 4, 5, 7};
    int[] array12 = {1, 3, 4, 5, 7};
    resultArr = add(array11, array12);
    for (int i = 0; i < resultArr.length; i++) {
        System.out.println(resultArr[i]);
    }

}

public static int[] add(int[] arr1, int[] arr2) {
    int arrLength1 = arr1.length;
    int arrLength2 = arr2.length;
    int[] resultArr;
    int smallerLength = 0;
    if (arrLength1 > arrLength2) {
        resultArr = Arrays.copyOf(arr1, arrLength1);
        smallerLength = arrLength2;
    } else {
        resultArr = Arrays.copyOf(arr2, arrLength2);
        smallerLength = arrLength1;
    }
    for (int i = 0; i < smallerLength; i++) {
        resultArr[i] = arr1[i] + arr2[i];

    }

    return resultArr;
}

} }

 public static int[] applyOn2Array(IntBinaryOperator operator, int[] b, int a[]) {
     int maxLength = b.length > a.length? b.length:a.length;       
     int res[] = null;
     try {
         res = IntStream.range(0, maxLength)
         .map(index -> operator.applyAsInt(a.length > index?a[index]:0,b.length > index? b[index]:0))
         .toArray();
     }catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Error:"+e.getMessage());
     }
     return res;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM