views:

287

answers:

7

CodingBat > Java > Array-1 > reverse3:

Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.

public int[] reverse3(int[] nums) {
    int[] values = new int[3];
    for (int i = 0; i <= nums.length - 1; i++) {
        for (int j = nums.length-1; j >= 0; j--) {
            values[i] = nums[j];
        }
    }
    return values;
}

I can't get this to work properly, usually the last int in the array, becomes every single int in the new array

+2  A: 

Firstly, while creating new array give it size of old array. Next, when you're reversing an array, you don't need two loops, just one:

int length = oldArray.length
for(int i = 0; i < length; i++)
{
  newArray[length-i-1] = oldArray[i]
}
Luno
A: 

You only want a single loop, but with indices going both ways:

public int[] reverse(int[] nums) {
    int[] back = new int[nums.length];
    int i,j;
    for (i=0,j=nums.length-1 ; i<nums.length ; i++,j--)
        back[i] = nums[j];
    return back;
}
Donal Fellows
A: 
  public int[] reverse3(int[] nums) {
  int[] values = new int[nums.length];
  for(int i=0; i<nums.length; i++) {
   values[nums.length  - (i + 1)]=nums[i];
  }
  return values;
  }
Mex
-1 for ArrayOutOfBoundException
Luno
+2  A: 

You don't want a two-level loop. Just have one loop:

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

or, alternately, just don't track j sepearately, and do this:

for(int i = 0; i < nums.length; i++) {
    values[i] = nums[nums.length - 1 - i];
}
Yuliy
Thanks, I tried doing this earlier but I also added j>0 in the for loop and it kept giving me an error so I gave up on the single loop and attempted to do two loops. Thank you for helping me see my mistake
A: 

In your code, for each value of i, you are setting target array elements at i to value in "nums" at j. That is how you end up with same value for all the elements at the end of all iterations. First of all, very bad logic to have two loops for a simple swap algorithm such as :

public static void reverse(int[] b) {
   int left  = 0;          // index of leftmost element
   int right = b.length-1; // index of rightmost element

   while (left < right) {
      // exchange the left and right elements
      int temp = b[left]; 
      b[left]  = b[right]; 
      b[right] = temp;

      // move the bounds toward the center
      left++;
      right--;
   }
}//endmethod reverse

or simplified:

for (int left=0, int right=b.length-1; left<right; left++, right--) {
    // exchange the first and last
    int temp = b[left]; b[left]  = b[right]; b[right] = temp;
}

Why go through all this pain, why dont you trust Java's built-in APIs and do something like

public static Object[] reverse(Object[] array)
{
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
return list.toArray();
}
ring bearer
The OP (or the OP's tutor) states that the solution should return a new array as opposed to swapping elements of the original one.
Adamski
The last solution does not work as int[] can't be casted to Object[]. Correct me if i am wrong.
Willi
@will, that was just an example! not i wrote "something like"
ring bearer
The last solution *can* be made to work with the help of a wrapper such as: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/primitives/Ints.html
finnw
+3  A: 

Unless this is a homework, why not just use Apache ArrayUtils'

ArrayUtils.reverse(nums)

Never re-invent the wheel :)

Mihir Mathuria
Including a separate library with your program seems like overkill for this.
R. Bemrose
Unless it is a homework it pays to use Apache utils, there's a lot more on that lib and it's not that big.I always add Apache utils on my code whenever I need, it saves a lot of time.
Lucass
You need to get an external library rather than write two lines of code? Okay, I guess if that works for you. But what do you do when you need to write two lines of code that are NOT available in an open source library?
Jay
Well, look at it this way: the author could have easily avoided all the turmoil of writing the (buggy) code, trying to debug it, posting the question on SO and all the back and forth just by using the APIThis alone would have convinced me to use existing 3rd party APIs. ON top of that you get a suite of well-documented, well-tested and very frequently used functions for any future requirement.And there, you have a winner :)
Mihir Mathuria
Guys, this is a CodingBat practice question. Libraries etc definitely not helpful for learning Java arrays basics. In fact, they're not even supposed to use a loop just yet (hence the array is fixed at length 3). See my answer.
polygenelubricants
+2  A: 

The length of the input int[] is fixed at 3? Then it doesn't get any simpler than this.

public int[] reverse3(int[] nums) {
    return new int[] { nums[2], nums[1], nums[0] };
}

See also:

  • CodingBat/Java/Array-1/reverse3
    • Note that Array-1 is "Basic array problems -- no loops." You can use a loop if you want, but it's designed NOT to be solved using loops.
polygenelubricants