# Cracking the coding interview--Q20.2

Hawstein | February 24, 2013

## 题目

Write a method to shuffle a deck of cards. It must be a perfect shuffle - in other words, each 52! permutations of the deck has to be equally likely. Assume that you are given a random number generator which is perfect.

## 解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <cstdlib>
using namespace std;

void Swap(int &a, int &b){// 有可能swap同一变量，不能用异或版本
int t = a;
a = b;
b = t;
}
void RandomShuffle(int a[], int n){
for(int i=0; i<n; ++i){
int j = rand() % (n-i) + i;// 产生i到n-1间的随机数
Swap(a[i], a[j]);
}
}
int main(){
srand((unsigned)time(0));
int n = 9;
int a[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9
};
RandomShuffle(a, n);
for(int i=0; i<n; ++i)
cout<<a[i]<<endl;
return 0;
}


Cracking the coding interview–问题与解答

https://github.com/Hawstein/cracking-the-coding-interview