import java.util.Random;
public static final Random gen = new Random();
// version for array of ints
public static void shuffle (int[] array) {
int n = array.length;
while (n > 1) {
//decrements after using the value
int k = gen.nextInt(n--);
int temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
// version for array of references
public static void shuffle (Object[] array) {
int n = array.length;
while (n > 1) {
//decrements after using the value
int k = gen.nextInt(n--);
Object temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
Knuth Shuffle (aka the Fisher-Yates shuffle)
Create a random permutation of an array.


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.