0

I am trying to write a method that takes an array, and adds adjacent cells together to produce a new array. It's easier to explain with examples:

{11, 4, 3, 18, 23, 9} --> {15, 21, 32}

{5, 5, 21, 13, 1} --> {10, 34} (the sixth cell is just ignored)

public static int[] collapse(int[] a) {
    int[] b = new int[a.length / 2];
    for (int j = 0 ; j < (a.length - 1) ; j+2) {    //goes thru original array
        for (int i = 0 ; i < b.length ; i++) {      //populates new array
            b[i] = a[j] + a[j+1];
        }
    }
    return b;
}

I figured this required using nested for-loops, the first one to go thru the original array, and the second one to populate the new array. I know that the j+2 in the first for-loop is syntactically incorrect, but I cannot figure out another way to accomplish the same idea.

0

3 Answers 3

2

Problem #1: The third expression in a for usually needs to be something that modifies the index. j+2 by itself doesn't do that; j = j + 2 would. (Or j += 2.)

Problem #2: You do not want a nested for loop. What this does is: first it sets j to 0 and lets i go through the whole b array. Then it increments j (after you fix the first problem) and lets i go through the whole b array again. This isn't what you want; you want them to be increased in parallel.

One way is just to declare i as a variable outside the loop:

int i = 0;
for (int j = 0; j < a.length - 1; j += 2) {
     b[i++] = a[j] + a[j + 1];
}

making sure the body of the loop increments i. Or, you can get fancy:

for (int i = 0, j = 0; j < a.length - 1; i++, j += 2) {
    b[i] = a[j] + a[j + 1];
}

and let the for increment both indexes.

Sign up to request clarification or add additional context in comments.

Comments

1

Don't use two loops. Just keep a counter (outputIndex) that represents your position in the output array, and increment it each time after you use it:

public static int[] collapse(int[] a) {
    int[] b = new int[a.length / 2];
    int outputIndex = 0;
    for (int j = 1 ; j < a.length ; j+=2) {    //goes thru original array
        b[outputIndex++] = a[j - 1] + a[j];
    }
    return b;
}

Also, I started the loop at j = 1, so that it handles the case where you are missing the last item to be added. Just remember that the two items you are adding are at [j-1] and [j], not [j] and [j+1].

Comments

0

Maybe you meant j=j+2, not just j+2?

In fact, this can be done with one for loop.

for(int i = 0; i < oldArray.length - oldArray.length % 2; i+=2) {
    newArray[i/2] = oldArray[i] + oldArray[i+1]
}

The i < oldArray.length - oldArray.length % 2 ensures that for an odd array, the last element is ignored.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.