Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling a deck of cards

I'm making a Deck class for a C++ program. It needs to have two methods: one to pop a card off the top of the deck, another to shuffle the deck. I'm concerned with the latter.

Cards are represented as integers 1 to 52 inclusive. What is the fastest algorithm to shuffle the deck (assuming a 'good' level of randomness)?

like image 747
oadams Avatar asked Nov 02 '10 06:11

oadams


People also ask

What is the best way to shuffle a deck of cards?

According to the video, the familiar "riffle method" of shuffling trumps all the others. It involves holding half of the deck in each hand and then using the thumbs to alternate the cards. But you've got to shuffle seven times to get the job done.

What does it mean to shuffle a deck of cards?

Shuffling is a procedure used to randomize a deck of playing cards to provide an element of chance in card games. Shuffling is often followed by a cut, to help ensure that the shuffler has not manipulated the outcome.

What are the odds of shuffling a deck of cards in order?

Asked by: Chris Nicolson, Isle of Skye If you truly randomise the deck, the chances of the cards ending up in perfect order - spades, then hearts, diamonds and clubs - are around 1 in 10 to the power 68 (or 1 followed by 68 zeros). That's a huge number, roughly equal to the number of atoms in our galaxy.

How many shuffles does it take to randomize a deck?

Summary. Based on this analysis, Diaconis has written that "seven shuffles are necessary and suffice to approximately randomize 52 cards." Of course, our technique has just given an upper bound for the distance between Rk and U .


1 Answers

If you wish to implement the shuffle yourself, a very straightforward but also functional shuffling algorithm: Fisher–Yates shuffle.

To shuffle an array a of n elements:

for i from n − 1 downto 1 do
   j ← random integer with 0 ≤ j ≤ i
   exchange a[j] and a[i]

Of course, the C++ standard library also has things like this implemented for you, such as std::random_shuffle, included via the <algorithm> header.

like image 96
Amber Avatar answered Sep 24 '22 02:09

Amber