扑克牌的完美洗牌算法

思路:

    递归思想。我们有n张牌,不妨先假设有一个洗牌函数shuffle(....),能完美的洗出n-1张牌 。拿第n张牌来打乱前面n-1的洗牌顺序,从而得到n张牌的最终结果。

代码如下:

 1 #include <iostream>
 2 #include <cstdlib>
 3 using namespace std;
 4 
 5 //随机指定区域内的数
 6 int MyRand(int low, int high)
 7 {
 8     return low + rand() % (high - low + 1);
 9 }
10 
11 int* shuffle(int* cards, int n)
12 {
13     if (n <= 0)
14         return cards;
15 
16     shuffle(cards, n - 1);
17     int rand = MyRand(0, n);
18 
19     int temp = cards[rand];
20     cards[rand] = cards[n];
21     cards[n] = temp;
22 
23     return cards;
24 }
25 
26 int main()
27 {
28     for (int k = 1; k <= 10; k++)
29     {
30         int cards[52] = {
31             1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
32             14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
33             25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
34             36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
35             47, 48, 49, 50, 51, 52,
36         };
37         cout << endl;
38         shuffle(cards, 52);//  洗牌
39         for (int i = 1; i <= 52; i++)
40         {
41             cout << cards[i - 1] << " ";
42             if (i % 13 == 0)
43                 cout << endl;
44         }
45     }
46     cout << endl;
47     system("PAUSE");
48     return 0;
49 }

输出结果:

 1 4 18 17 14 36 6 41 20 26 29 1 39 12
 2 51 48 49 13 27 10 34 31 47 8 52 45 35
 3 40 4 38 25 3 24 19 22 21 44 32 30 15
 4 50 16 2 33 11 5 7 23 46 42 37 43 9
 5 
 6 11 36 41 28 48 35 29 30 10 15 40 44 31
 7 26 33 8 7 12 32 23 14 46 45 6 21 24
 8 3 25 1 13 18 20 39 52 5 4 47 17 42
 9 50 16 2 37 38 9 19 43 27 34 28 22 51
10 
11 2 17 33 13 19 32 44 8 12 23 52 51 45
12 4 26 1 14 38 3 43 21 39 11 9 42 46
13 35 34 31 47 29 41 18 25 40 48 6 10 30
14 36 15 24 49 37 5 27 28 50 49 16 20 22
15 
16 31 12 5 39 35 47 9 23 16 41 20 24 48
17 21 11 30 13 7 43 38 49 40 46 19 50 52
18 44 14 6 45 18 1 17 32 4 28 27 8 2
19 36 33 15 42 34 29 25 37 10 26 51 22 7
20 
21 47 23 11 36 18 40 25 32 39 7 42 4 22
22 48 49 33 3 30 43 41 12 6 15 24 37 28
23 27 50 51 19 16 29 3 5 2 26 10 35 52
24 1 38 45 34 21 13 31 17 14 46 9 8 44
25 
26 ........

从结果来看上去很完美,剩下就是要在随机函数上做文章了,如果有一个完美的随机数发生器,那么这就是一个完美的洗牌算法。

通常递归的方法都能最换成迭代法,代码如下:

 1 void shuffle2(int* cards, int n)
 2 {
 3     // 随机i-1中的任意一个数与i交换
 4     for (int i = 0; i < n; i++)
 5     {
 6         int rand = MyRand(0, i);
 7         int temp = cards[rand];
 8         cards[rand] = cards[i];
 9         cards[i] = temp;
10     }
11 }

Done!还不赖~~~

原文地址:https://www.cnblogs.com/borey/p/5626144.html