next up previous
Next: Sort the deck Up: Assignment 10: Cards and Previous: Make a deck

Shuffle the deck


 
Figure 1: An array of cards is really an array of references to cards, which is why the cards have to be allocated with new individually. It is also why you can swap cards just by swapping references, rather than having to copy the data (rank and suit) in each object.
\begin{figure}
\centerline{
\psfig {figure=fig_ass10.eps,height=3.0in}
}\end{figure}

1.
Write a static method called swapCards that takes two indices as arguments and that switches the two cards at the indicated positions. Remember that you can switch objects by switching the references to the objects rather than having to move the data (instance variables) in the objects. If the previous paragraph doesn't make sense to you, see the figure. If it still doesn't make sense, talk to Allen or a TA.

2.
The following method generates a random number between low and high, including both low and high. As you type it in, be sure you understand how it works. Also, you might want to test it to make sure that you typed it correctly and I haven't messed up.

    public static int randomInt (int low, int high)
    {
        double x = Math.random() * (high - low + 1);
        return (int) x + low;
    }

3.
Use swapCard and randomInt to write a static method named shuffleDeck that takes an array of cards as an argument and shuffles the deck in such a way that every card has an equal probability of being at any position in the deck. As with the other methods that operate on decks, your code should not assume that the deck has 52 cards.


next up previous
Next: Sort the deck Up: Assignment 10: Cards and Previous: Make a deck
Allen B. Downey
4/21/1998