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.