FAQ 4e
Updated: 1/10/00
>>>>>> How do I shuffle a deck?
===============================
Shuffling a deck of cards is a classic problem. It's loads easier with
the java Vector() class. Create your cards as objects, then add them
individually to a Vector. When you want to shuffle, start pulling them
out at random, then toss them into a fresh Vector. When you run out
of cards, voila you are finished.
// 'CardApplet.java' code file
import java.applet.*;
import java.awt.*;
import java.util.*;
class Card extends Integer{} // an object with a number
class Deck extends Vector{} // a list of objects (cards)
class CardApplet extends Applet {
final static int CARD_COUNT = 100; // number of cards
Deck firstDeck = new Deck();
Deck secondDeck = new Deck();
MyRandom randMaker; // see FAQ_3d
CardApplet(){}
public void init(){
Card temp;
int ix;
// create an unshuffled deck
for (ix=0;ix<CARD_COUNT;ix++) firstDeck.addElement(new Card(ix));
// move cards from original to shuffled deck
while (firstDeck.size()>0) {
ix = randMaker.rand(firstDeck.size()); // random selection
temp = (Card)firstDeck.elementAt(ix);
firstDeck.removeElement(temp);
secondDeck.addElement(temp);
}
}
public void paint(Graphics g){ // display results
Card temp;
int ix;
for (ix=0;ix<100;ix++) {
temp = (Card)secondDeck.elementAt(ix);
g.drawString("c"+temp.intValue(),5+25*(ix%10),15+10*(ix/10));
}
}
}
You may be boggled by the drawString line in paint(). The last two values are
the x/y coordinates at which the string will be drawn. Essentially, I draw the
numbers left to right, then every tenth number I drop down one row.
:::::: final static values
==========================
final static values are constants. This value is the same every time you use
it in your code. It will cause an error if you try to change it.