11,704,107 members (52,130 online)
Tip/Trick

# Random extraction of 5 cards from a deck

, 26 Jan 2010 CPOL 11K 2
 Rate this:
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:
```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:
```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;
}
```

## Share

 Software Developer (Senior) AEM S.p.A. Italy

Debugging? Klingons do not debug. Our software does not coddle the weak. Bugs are good for building character in the user.
-- The Klingon programmer

Beelzebub for his friends [^].

## You may also be interested in...

 First Prev Next
 Thank you for posting something like this... Raja Sekhar S16-Jul-13 23:59 Raja Sekhar S 16-Jul-13 23:59
 Re: Thank you for posting something like this... CPallini17-Jul-13 0:26 CPallini 17-Jul-13 0:26
 great article PraveenKumarReddyChinta4-Dec-12 1:19 PraveenKumarReddyChinta 4-Dec-12 1:19
 Re: great article CPallini4-Dec-12 2:08 CPallini 4-Dec-12 2:08
 Very useful PraveenKumarReddyChinta4-Dec-12 1:18 PraveenKumarReddyChinta 4-Dec-12 1:18
 Thank you so much for posting this. Very userful!.
 Re: Very useful CPallini4-Dec-12 2:06 CPallini 4-Dec-12 2:06
 Very helpful way to solve this problem. Thank you. ColinBinWang7-Aug-11 16:12 ColinBinWang 7-Aug-11 16:12
 Re: Very helpful way to solve this problem. Thank you. CPallini2-May-12 21:24 CPallini 2-May-12 21:24
 Last Visit: 31-Dec-99 18:00     Last Update: 28-Aug-15 5:49 Refresh 1