Click here to Skip to main content
Click here to Skip to main content

Random extraction of 5 cards from a deck

By , 26 Jan 2010
Rate this:
Please Sign up or sign in to vote.
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++)
// '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;
// 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;
Smile | :)


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

About the Author

Software Developer (Senior) AEM S.p.A.
Italy 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 [^].

Follow on   LinkedIn

Comments and Discussions

QuestionThank you for posting something like this... PinprofessionalRaja Sekhar S16-Jul-13 23:59 
AnswerRe: Thank you for posting something like this... PinmvpCPallini17-Jul-13 0:26 
Generalgreat article PinmemberPraveenKumarReddyChinta4-Dec-12 1:19 
GeneralRe: great article PinmvpCPallini4-Dec-12 2:08 
QuestionVery useful PinmemberPraveenKumarReddyChinta4-Dec-12 1:18 
AnswerRe: Very useful PinmvpCPallini4-Dec-12 2:06 
GeneralVery helpful way to solve this problem. Thank you. PinmemberColinBinWang7-Aug-11 16:12 
GeneralRe: Very helpful way to solve this problem. Thank you. PinmvpCPallini2-May-12 21:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 26 Jan 2010
Article Copyright 2010 by CPallini
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid