0

If I have an array int[] a = new int[]{1, 2, 3}; and another 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?

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

dsdouglous
  • 93
  • 2
  • 4
  • 9
  • Duplicate of: [How to concatenate two arrays in Java?](http://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java) – Mr. Polywhirl Feb 11 '14 at 02:42
  • 2
    @Mr.Polywhirl This in not about concatenation. Please re-read the question. – The Guy with The Hat Feb 11 '14 at 02:44
  • @dsdouglous could you please add more code/context to how you are calling the addition of the arrays? Would help me provide a better answer. – xlm Feb 11 '14 at 02:50
  • Yeah, sorry for the confusion. – Mr. Polywhirl Feb 11 '14 at 03:07
  • @dsdouglous thanks, you might want to check your code though i.e. in else clause you refer to variable `c` which is only declared/in-scope for in the if-then clause. Also I think you have used `added` interchangeably with `c` – xlm Feb 11 '14 at 03:17

7 Answers7

4

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.

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]
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • +1 This is more or less what I was going to say. You could use the ternary instead of `Math.max`: `a.length < b.length ? b.length : a.length`. Not sure which one is more obvious. Most people would also recommend some braces for the `if` statements, or at least put the then block on the same line. Regardless of the nitpicks, much simpler and shorter this way. – jpmc26 Feb 11 '14 at 03:14
1
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.

Result:

2    4    6    4
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
0

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. So you can't check null in this case you have to check the length of the shorter array.

Also I'm not sure how you get {4, 4} because I need more code to understand what is going on.

But anyway here's a solution to avoid 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;
}
xlm
  • 6,854
  • 14
  • 53
  • 55
  • Would I check this by saying "if(a[i] == null) { c[i] = b[i] } or would this not work because you can't compare ints to null? If not, how would I compare them? – dsdouglous Feb 11 '14 at 02:42
  • @user3279087 hang on there's a few more issues with code, updating now. – xlm Feb 11 '14 at 02:43
  • @dsdouglous if you like to find out why your code was returning {4,4} please provide more code and I'll help analyze. Otherwise you should find the method above should do what you intend. – xlm Feb 11 '14 at 03:02
0

You've gone out of bounds because program is looking for number on the third place in the "a" and "b" array. In the "a" array it's number 3, but array "b" has no such number so you get an error index out of bounds. 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.

msmolcic
  • 6,407
  • 8
  • 32
  • 56
0

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. 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:

    ...

    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:

    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.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
0

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;

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

}

Harish
  • 3,343
  • 15
  • 54
  • 75
0
 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;
 }
Pulkit
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 07 '21 at 18:55