18.2 Write a method to shuffle a deck of cards. It must is a perfect shuffle-in other words, each of the 52! Permutations of the deck have to be equally likely. Assume that's given a random number generator which is perfect.
This problem let us achieve a shuffle algorithm, in fact, the principle of shuffle is very simple, that is, each card with a random position of the card exchange position can be, then there are two ways to implement, recursive and iterative. We first look at the recursive method, specifically with the idea of backtracking, we start from the i=51, and then each time into the recursive function, to i=0, then return to the I=1, and then the [0,i] between the random card exchange position, and then a layer of back, always back to i= 51, so that each card we have randomly exchanged positions, so as to achieve the purpose of shuffling:
Solution One:
void Shuffle (vector<intint i) { if0return ; 1 ); int 1 ); Swap (Cards[k], cards[i]);}
We can also use an iterative approach, using a for loop to swap the position of each card and the random position:
Solution Two:
void Shuffle (vector<int> &cards) { for (int0; I < Cards.size (); + +i) {int1); Swap (Cards[k], cards[i]);} }
Careercup all in one topic summary
[Careercup] 18.2 Shuffle Cards Shuffle