Nyam
Nyam

Reputation: 43

Java - Returning a new array with elements in even positions from a given array

I am new to Java and I am stuck on a problem that requires me to return a new array containing only the even-numbered elements from a given array. The method should consider arrays of odd or even length and zero or one element in the array. The length should be exact so there are no extra zeros at the end of the array.

public static int[] everyOther(int[] arr){
    int nArrayL;
    if (arr.length < 2){
        return arr;
    }  
    else{
        if (arr.length % 2 == 0){
            nArrayL = arr.length / 2;
        }
        else{nArrayL = arr.length / 2 + 1;
        }
    }
    int[] nextArray = new int[nArrayL];
    int count = 0;
    for(int x = 0; x < arr.length; x +=2){
        nextArray[count] = x;
        count++;
    }
    return nextArray;
}

Here is my attempt to the problem and it is compiling but not passing.

Upvotes: 4

Views: 748

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201477

As already noted, the mistake was copying x into the array (instead of arr[x]). However, you can eliminate count (because it is always one half of x). You could also invert that identity (e.g. i and i*2 as indices). Simplifying the code then leaves something like,

public static int[] everyOther(int[] arr) {
    if (arr.length < 2) {
        return arr;
    }
    int[] nextArray = new int[(arr.length + 1) / 2];
    for (int i = 0; i < nextArray.length; i++) {
        nextArray[i] = arr[i * 2];
    }
    return nextArray;
}

And if you're using Java 8+, you might use an IntStream and then map each index with the same algorithm. Like,

public static int[] everyOther(int[] arr) {
    if (arr.length < 2) {
        return arr;
    }
    return IntStream.range(0, (arr.length + 1) / 2).map(i -> arr[i * 2]).toArray();
}

Upvotes: 2

Willis Blackburn
Willis Blackburn

Reputation: 8204

Your approach is basically correct. I think the only error is that you're copying the array index into the output array, instead of the element at the array index.

A couple of other suggestions:

  • You don't need the "else" because you're returning in the "if" statement. The whole rest of the function is "else."
  • Instead of handling the odd and even cases separately, you can just do (arr.length + 1) / 2.

Upvotes: 1

Related Questions