Tuesday, October 6, 2015

[20.2] Perfect shuffle a deck of cards

1. Example


Not Inclusive 
(int) ( Math.random() *(higher-lower) ) + lower
Equally likely=>rand(), 
Iterating and SWAP prevent the same card being selected 
52! permutations of the deck has to be equally likely
==> cannot pick the same card twice
[1] [2] [3] [4] [5]
[4]
[1] [2] [3] [X] [5]


Iter1: Swap [1] and [21]
[1][2][3].......[52]
[21][2][3]......[1].....[52]
Iter2: Swap [2] and [31]
[1][2][3].......[52]
[21][31][3]......[31].....[52]

Math.random()=>  [0.0, 1.0)
(int)  (  Math.random() * (card.length - i)  ) + i
i = 5 
[0,1) * (52-5) + 5 = [5, 52) including current index and len-2 index

2. Implementation


public static void shuffleArray(  int[] cards )
{
      int temp, pickIndex;
      for (int i = 0 ; i < cards.length; i++)
      {
          pickIndex = (int)  (  Math.random() * (card.length - i)  ) + i;
          temp = cards[pickIndex];
          cards[pickIndex] = cards[i];
          cards[i] = tmp;
      } 
} 
3. Similar Ones

No comments:

Post a Comment