Friday, January 29, 2016

Shuffle a deck of cards

Shuffle a deck of cards

Problem:
Write a method to shuffle a deck of cards. 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.
Solution:
This is a very well known interview question, and a well known algorithm. If you aren’t one of the lucky few to have already know this algorithm, read on.
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.
Array: [1] [2] [3] [4] [5]
Randomly select 4: [4] [?] [?] [?] [?]
Mark element as dead: [1] [2] [3] [X] [5]
The tricky part is, how do we mark [4] as dead such that we prevent that element from being picked again? One way to do it is to swap the now-dead [4] with the first element in the array:
Array: [1] [2] [3] [4] [5]
Randomly select 4: [4] [?] [?] [?] [?]
Swap dead element: [X] [2] [3] [1] [5]
Array: [X] [2] [3] [1] [5]
Randomly select 3: [4] [3] [?] [?] [?]
Swap dead element: [X] [X] [2] [1] [5]
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 etc elements are dead. We can also optimize this by merging the shuffled array and the original array.
Randomly select 4: [4] [2] [3] [1] [5]
Randomly select 3: [4] [3] [2] [1] [5]
This is an easy algorithm to implement iteratively:
1
2
3
4
5
6
7
8
9
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;
  }
}
Click here for more Programming Interview Questions

No comments:

Post a Comment