首页 > 代码库 > CC150 20.2

CC150 20.2

20.2 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.

// Randomly generate a int k from 1(inclusive) to n(inclusive).
int random(int n);

class DeckShuffle()
{
  // Init a deck with 52 cards.
  private int[] init()
  
  // Swap element
  private void swap(int[] a, int from, int to)
  
  int[] next()
  {  
    int[] deck = init();
    
    for (int i = 0 ; i < deck.length - 1 ; i ++)
    {
      int pos = random(52 - i);
      swap(deck, pos, i);
    }
    
    return deck;
  }  
}


CC150 20.2