今天看到了两个洗牌算法,用c#实现了下:
第一个:
1 public void Shuffle()
2 {
3
4 int[] cards = new int[54] { 0, 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, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 };
5 //创建一个临时的扑克牌组
6 int[] newCards = new Card[54];
7 //bool变量数组
8 bool[] assigned = new bool[54];
9
10 Random sourceGen = new Random();
11 for (int i = 0; i < 54; i++)
12 {
13 int destCard = 0; //随机数保存空间
14 bool foundCard = false;
15 while (foundCard == false)
16 {
17 //生成一个0到54之间的随机数
18 destCard = sourceGen.Next(54);
19 if (assigned[destCard] == false)
20 {
21 foundCard = true;
22 }
23 }
24 assigned[destCard] = true;
25 newcards[destCard] = cards[i];
26 }
2 {
3
4 int[] cards = new int[54] { 0, 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, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 };
5 //创建一个临时的扑克牌组
6 int[] newCards = new Card[54];
7 //bool变量数组
8 bool[] assigned = new bool[54];
9
10 Random sourceGen = new Random();
11 for (int i = 0; i < 54; i++)
12 {
13 int destCard = 0; //随机数保存空间
14 bool foundCard = false;
15 while (foundCard == false)
16 {
17 //生成一个0到54之间的随机数
18 destCard = sourceGen.Next(54);
19 if (assigned[destCard] == false)
20 {
21 foundCard = true;
22 }
23 }
24 assigned[destCard] = true;
25 newcards[destCard] = cards[i];
26 }
第二个:
1 public void Reshuffle()
2 {
3 int[] cards = new int[54] { 0, 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, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 };
4 Random ram = new Random();
5 int currentIndex;
6 int tempValue;
7 for (int i = 0; i < 54; i++)
8 {
9 currentIndex = ram.Next(0, 54 - i);
10 tempValue = cards[currentIndex];
11 cards[currentIndex] = cards[53 - i];
12 cards[53 - i] = tempValue;
13 }
14 }
15
2 {
3 int[] cards = new int[54] { 0, 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, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 };
4 Random ram = new Random();
5 int currentIndex;
6 int tempValue;
7 for (int i = 0; i < 54; i++)
8 {
9 currentIndex = ram.Next(0, 54 - i);
10 tempValue = cards[currentIndex];
11 cards[currentIndex] = cards[53 - i];
12 cards[53 - i] = tempValue;
13 }
14 }
15
相比一下,第二个更简单,更高效!