-4

The following code shuffles playing cards in a game. I have to explain what the code does in a presentation. I am a newbie in Java coding, so can anyone please explain to me the following code line by line:

// Deck shuffling method
public void shuffleDeck() {
    //Seed the Random instance with nanoTime
    Random random = new Random(System.nanoTime());
    for(int i = 0; i < 52; i++) {
        int swapIndex = random.nextInt(52);
        if (swapIndex != i) {
            PlayingCard temp = cardDeckArray[i];
            cardDeckArray[i] = cardDeckArray[swapIndex];
            cardDeckArray[swapIndex] = temp;
        }
    }
    cardIndex = 0; //Next card to be pulled off the deck
}
amit
  • 175,853
  • 27
  • 231
  • 333
  • 1
    I'm voting to reopen. I don't understand why is it "too broad", and I understand how a novice programmer can easily get confused by the repeated swaps. – amit Mar 02 '15 at 09:34

1 Answers1

3

This is a shuffle of a deck, at each iteration you swap two cards at random, and it will result in some random permutation of the deck.

However, this algorithm is flawed and biased, there are some permutations that are more likely to be generated than others, to use an unbiased shuffle, you should use fisher-yates shuffle (which is basically the same idea, but generate a random number between i to 52, instead between 0 to 52)

The reason and results of this bias is discussed thoroughly in the thread: What distribution do you get from this broken random shuffle?

Community
  • 1
  • 1
amit
  • 175,853
  • 27
  • 231
  • 333