Comparison of array randomization Methods

Source: Internet
Author: User

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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.