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)?
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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With