There are probably a bazillion ways to shuffle a deck of cards. How about this:
public void shuffleDeck()
{
int index = 1;
int val;
Random rnd = new Random();
// Clear out the array
System.Array.Clear(deck, 0, deck.Length);
// DECKSIZE is a symbolic constant set to 52. If another
// game using more than one deck is used (e.g., canasta)
// this could be changed
while (index != DECKSIZE + 1) {
val = rnd.Next(DECKSIZE + 1); // Values between 1 and 52
if (deck[val] == 0) // Empty card element??
{
deck[val] = index; // Yep,assign it a card place
index++; // Get ready for next card
}
}
}
This code assumes deck[] has already been set elsewhere to DECKSIZE + 1 elements. I use the "+1" because I want the cards to run from 1 through 52. Using a zero-based array would go from 0-51. (I have some visual card elements that make non-zero easier to use.)
So how does it work? (You can find the full details in my book.) Suppose the first pass generates the random value 18 for val. The code examines element 18 to see if a value is already there. If not, the element value is 0 and the value of index (1) is assigned to element 18. My algorithm interprets this as the Ace of Spades is located at element 18. On the next pass, suppose val is 42. If that element is unused (0), deck[42] gets 2 (the 2 of spades) assigned into it since that's the current value of index. Now suppose the third pass generates 18 again. Now the test shows deck[18] is non-zero so that space is already filled. It will generate another value to place the third card, and so on.
As the array fills up with cards, there are more and more "collisions" with used deck elements. Still, it rarely takes more than 300 passes through the loop to "shuffle" the deck. While I'm sure there are more efficient algorithms, this is an easy one to teach.
Dr. Purdum
Jack Purdum, Ph.D.
Author: Beginning C# 3.0: Introduction to Object Oriented Programming (and 14 other programming texts)
|