How to get a number of different random numbers - shuffle algorithm

First a question to ponder: has an array of size 100, and 100 which elements are arranged in order from 1 to, how to select a random number from the inside?

The simplest method is a method using the system  Math.random() * 100 , so that you can get a random number from 0 to 99, and then to a position corresponding to the array to find.

Next, thinking about a problem:  There is an array of size 100, which elements are arranged in sequence from 1 to 100, how to select a random number from the inside 50?

Note that the number can not be repeated!

If based on the above ideas, your first thought is: random 50 times not on the list?

However, doing so there is a very obvious bug: the number is repeated.

repair it a little?

Get an array, each time the random number out of the previous comparison, to see if there have been.

This is possible!

However, there is still a small problem, consider the extreme case: there is an array of size 100, which elements are arranged in order from 1 to 100, how to select a random number of 99 from the inside .

If you follow the above method, the more backward the selected number has already been selected with probability of repetition of the higher numbers, which will cause the number of digits if the array is large, is also a great choice of words, the number of repetitions will be on the order of great.

This time we need to change a line of thought, if the first element of the array inside the upset , then press 50 before the order of selection can not it?

Yes!

But we have to pay attention to what is chaos?

A pack of cards with 54 cards, there are 54! Permutations way. Refers to the so-called upset operation you performed, should be able to equal probability to generate one of these 54! Kinds of results.

Shuffling algorithm can do this.

Shuffling algorithm

Fisher-Yates shuffle algorithm proposed by Ronald Fisher and Frank Yates in 1938 and in 1964 adapted to apply to computer programming version of Richard Durstenfeld.

This algorithm is well understood but very fast hardware, popular explanation is: the number of the last preceding and a number n-1 of any number of the exchange, and then the number of any preceding penultimate n-2 number of a number of exchange. . .

It can be proved that this is equal probability to generate a permutation.
prove:
Is selected from the i-th probability is not selected when m = i-1 before the position element selected elements m the probability P * i-th position of the selected probability multiplicative m can be turned into 1 / n, i.e.,
$$\frac{n-1}{n} * \frac{n-2}{n-1}  \cdots \frac{i}{i+1} * \frac{1}{i} = \frac{1}{n}$$
Visible nothing to do with i.
Intuitive understanding, corresponding to n individual ballot, nothing to do with the order, everyone able to get the probability of an element are equal.
 
 

Guess you like

Origin www.cnblogs.com/lfri/p/12195490.html