Comparison of array randomization Methods
Today we have encountered the array randomization problem. We need to change the element sequence in the array and make the probability of occurrence of each sequence equal probability.
The solutions obtained through online search can be roughly divided into two types:
Solution 1:
Public static int [] RandomizeArray (int [] array) {Random rgen = new Random (); // Random number generator for (int I = 0; I
Solution 2:
Public static int [] RandomizeArray (int [] array) {Random rnd = new Random (); // Random number generator for (int I = array. length-1; I> 0; I --) {int index = rnd. nextInt (I + 1); // Simple swapint a = array [index]; array [index] = array [I]; array [I] = a;} return array ;}
These two algorithms are implemented based on the order of exchange elements. The difference lies in the cyclic condition. I have written some test code for these two algorithms. The test shows that the appearance of various sequences in method 1 is not equal probability, while method 2 is a random algorithm with equal probability. The specific Mathematics proves that I am not doing this. If you are interested, try it.