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]; int i, deck_cards;
for (i=0; i< CARDS; i++)
card[i]=i;
deck_cards = CARDS;
for (i=0; i<5; i++)
{
int r = rand() % deck_cards;
int temp = card[r];
card[r] = card[deck_cards-1];
card[deck_cards-1] = temp;
deck_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++)
{
int r = rand() % (CARDS-i);
int temp = card[r];
card[r] = card[CARDS-1-i];
card[CARDS-1-i] = temp;
}
:)