Let's take a look at card games first. A card is composed of 52 different cards. It must generate non-repeated cards during licensing and the shuffling process must be fair, that is, 52! The order of cards should be equal to the probability. Obviously, the random numbers produced by this random arrangement must be evenly distributed and independent. The Code is as follows:
- Using System;
- Using System. Diagnostics;
-
- Namespace Lucifer. CSharp. Sample
- {
- Class Program
- {
- Static void Main (string [] args)
- {
- // Initialize the Board
- Int [] array = new int [52];
- For (int I = 0; I <array. Length; I ++)
- {
- Array = I;
- }
-
- // Shuffling
- Permute <int> (array );
-
- // Verify the Board
- For (int I = 0; I <array. Length; I ++)
- {
- Var value = array;
- For (int j = 0; j <array. Length; j ++)
- {
- If (j = I) continue;
- Debug. Assert (array [j]! = Value );
- }
- }
- }
-
- Static void Permute <T> (T [] array)
- {
- Random random = new Random ();
- For (int I = 1; I <array. Length; I ++)
- {
- Swap <T> (array, I, random. Next (0, I ));
- }
- }
-
- Static void Swap <T> (T [] array, int indexA, int indexB)
- {
- T temp = array [indexA];
- Array [indexA] = array [indexB];
- Array [indexB] = temp;
- }
- }
- }
Copy code
In the sample code, the Permute <T> (T [] array) method generates a random sequence. The first loop uses 1, 2, 3 ,..., N initializes the sequence. The second loop completes a random shuffling. In each iteration of the loop, the value of array [j] is exchanged (or may not be exchanged) between an element in the range [0, j] Where the array is located ).
However, do we have to ask if the Permute <T> (T [] array) method produces all the permutation probabilities?
Based on this algorithm, the answer is yes. Because there are N in total! Possible arrangement, while Swap <T> (array, I, random. Next (0, I); the different results of the Next method called by the N-1 are N! Type. However, in fact, the answer is no. Not all permutation is equal probability. The problem lies in the cute Pseudo-Random Number Generator (Pseudo-Random Number Generator. The randomness of the PRNG largely limits the randomness of the random sequence. Therefore, the above Code requires a better pseudo-random number generator to make the actual situation more consistent with the theory. However, good PRNG performance often decreases, such as Mt19937 randomization algorithm.