# [Careercup] 18.2 Shuffle Cards Shuffle

Source: Internet
Author: User
Tags shuffle

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

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.