Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Random extraction of 5 cards from a deck

4.96/5 (11 votes)
26 Jan 2010CPOL 39K  
The question: How can I extract 5 random cards from a deck? (or similar), appears every now and then at the C/C++ forum.I use the following method:const int CARDS = 52;int card[CARDS]; // the 'card' array represents all of the cardsint i, deck_cards;// initializationfor (i=0;...
The question: "How can I extract 5 random cards from a deck?" (or similar), appears every now and then at the C/C++ forum.

I use the following method:
C++
const int CARDS = 52;
int card[CARDS]; // the 'card' array represents all of the cards
int i, deck_cards;
// initialization
for (i=0; i< CARDS; i++)
  card[i]=i;
// 'deck_cards' is the limit of the deck, it separates the 
// cards still inside the deck from the extracted ones
deck_cards = CARDS;

// random extraction of five cards
for (i=0; i<5; i++)
{
  // r is the newly extracted card index
  int r = rand() % deck_cards;

  // the trick is here: we move the choosen card at the current deck
  // limit and decrease the deck size by one.
  // this is accomplished swapping card[r] with card[deck_cards-1]
  int temp = card[r];
  card[r] = card[deck_cards-1];
  card[deck_cards-1] = temp;

  deck_cards--;
}
// now let't print out the random choosen cards
for (i=0; i<5; i++)
{
  printf("extracted card[%d]=%d\n", i, card[deck_cards+i]
}


Is worth noting we don't need at all the deck_cards variable, in the extraction loop:
C++
for (i=0; i<5; i++)
{ 
  // r is the newly extracted card index
  int r = rand() % (CARDS-i);  
  // swap card[r] with card[CARDS-1-i]
  int temp = card[r];
  card[r] = card[CARDS-1-i];
  card[CARDS-1-i] = temp;
}

:)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)