Random Shuffle of Array

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;

}

One thought on “Random Shuffle of Array

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s