Example of how to do a random shuffle of any Given Array. This example is based on a very famous shuffle algorithm knows as Fisher Yates Shuffle. Could be useful to implement in Poker Game to shuffle cards in Java.
Main Steps are:
1. loop from n to 1
2. generate the random index number k such that 0 <= k <= the length of array
3. swap the values between the random index and current iteration index
See below link for more details on this.
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
private static int[] shuffle(int[] a) {
Random rand = new Random();
for (int lc = a.length – 1; lc > 0; lc–) {
int shuffleIdx = rand.nextInt(lc + 1);
int v = a[shuffleIdx];
a[shuffleIdx] = a[lc];
a[lc] = v;
}
return a;
}
Advertisements