Skip to main content
Engineering LibreTexts

4.2: Shuffling Decks

  • Page ID
    15292
  • For most card games you need to be able to shuffle the deck; that is, put the cards in a random order. In Section 8.7 we saw how to generate random numbers, but it is not obvious how to use them to shuffle a deck.

    One possibility is to model the way humans shuffle, which is usually dividing the deck in two halves and then choosing alternately from each one. Since humans usually don’t shuffle perfectly, after about seven iterations the order of the deck is pretty well randomized.

    But a computer program would have the annoying property of doing a perfect shuffle every time, which is not very random. In fact, after eight perfect shuffles, you would find the deck back in the order you started in! (For more information, see https://en.Wikipedia.org/wiki/Faro_shuffle.)

    A better shuffling algorithm is to traverse the deck one card at a time, and at each iteration choose two cards and swap them. Here is an outline of how this algorithm works. To sketch the program, we will use a combination of Java statements and English. This technique is sometimes called pseudocode.

    for each index i {
        // choose a random number between i and length - 1
        // swap the ith card and the randomly-chosen card
    }
    

    The nice thing about pseudocode is that it often makes clear what methods you are going to need. In this case, we need a method that chooses a random integer between low and high, and a method that takes two indexes and swaps the cards at those positions. Methods like these are called helper methods, because they help you implement more complex algorithms.

    And this process – writing pseudocode first and then writing methods to make it work – is called top-down development (see https://en.Wikipedia.org/wiki/Top-down_and_bottom-up_design).

    One of the exercises at the end of the chapter asks you to write the helper methods randomInt and swapCards and use them to implement shuffle.

    • Was this article helpful?