0

I'm working on a project where we are creating an 'efficient shuffling' method that takes an array and shuffles the places of the values inside it. However, I am getting an out of bounds exception runtime error and I am not sure what is causing it.

public static void selectionShuffle(int[] values) {
   for(int k = values.length; k > 0; k--) {
     int[] temp = new int[k];
     double rand = Math.floor(Math.random() * k);
     int r = (int) rand;
     temp[r] = values[r];
     values[r] = values[k];  //here is where the outofbounds error resides
     values[k] = values[r];
   }
 }

This is the method and here is the code that is running it. This is given to me and should not be changed.

 private static final int SHUFFLE_COUNT = 1;
 private static final int VALUE_COUNT = 4;

 public static void main(String[] args) {
  System.out.println("Results of " + SHUFFLE_COUNT +
         " consecutive perfect shuffles:");
  int[] values2 = new int[VALUE_COUNT];
  for (int i = 0; i < values2.length; i++) {
   values2[i] = i;
   }
  for (int j = 1; j <= SHUFFLE_COUNT; j++) {
   selectionShuffle(values2);    //error is referenced here, when the method is called
   System.out.print("  " + j + ":");
   for (int k = 0; k < values2.length; k++) {
    System.out.print(" " + values2[k]);
   }
   System.out.println();
  }
  System.out.println();
 }

This code here is a bit segmented just to be read easier.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
OSG
  • 113
  • 5

1 Answers1

3

The line

for(int k = values.length

starts k out as being the length of values, but then

values[r] = values[k];  //here is where the outofbounds error resides

causes the exception, because Java arrays are zero-indexed.

You can fix this by changing your for loop to

for(int k = values.length-1; k >= 0; k--)
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • I feel pretty dumb now that I see that. I changed the definition statements from `[k]` to `[k-1]` and it worked, but that might be a cleaner edit. – OSG Apr 15 '15 at 19:36
  • Having a `for` loop that begins or ends at 0 is the idiomatic way to write the loop, but your way works too. – Eric J. Apr 15 '15 at 19:37