Write a method to shuffle a deck of cards - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Write a method to shuffle a deck of cards

Share This
It must be a perfect shuffle - in other words, each 52! permutations of the deck has to be equally likely. Assume that you are given a random number generator which is perfect.

Let’s start with a brute force approach: we could randomly selecting items and put them into a new array. We must make sure that we don’t pick the same item twice though by somehow marking the node as dead. 
 
The tricky part is, how do we mark an element as dead such that we prevent that element from being picked again? One way to do it is to swap the now-dead element with the first element in the array. By doing it this way, it’s much easier for the algorithm to “know” that the first k elements are dead than that the third, fourth, nineth, etc elements are dead. We can also optimize this by merging the shuffled array and the original array.

public static void shuffleArray(int[] cards) { int temp, index; for (int i = 0; i < cards.length; i++){ index = (int) (Math.random() * (cards.length - i)) + i; temp = cards[i]; cards[i] = cards[index]; cards[index] = temp; } }



Happy Exploring!

No comments:

Post a Comment