Home >Backend Development >PHP Tutorial >10 number random distribution algorithm
10 numbers are randomly divided into 10 positions. How to write such a random algorithm.
My idea: Generate a random number, and then take 10 positions modulo 10 + random number, but it doesn’t feel random enough. Is there any good algorithm?
For example:
1 2 3 4 5 6 7 8 9 10
2 1 4 3 9 7 8 6 5 10
. . .
(randomly arranged)
Added:
Provide a method:
Linear table of 10 numbers, random(10)=5, delete node 5
Linear table of 9 numbers, random(9)=2, delete node 2
. . . .
Last random sequence 5,2. . . . .
This feels quite random.
10 numbers are randomly divided into 10 positions. How to write such a random algorithm.
My idea: Generate a random number, and then take 10 positions modulo 10 + random number, but it doesn’t feel random enough. Is there any good algorithm?
For example:
1 2 3 4 5 6 7 8 9 10
2 1 4 3 9 7 8 6 5 10
. . .
(randomly arranged)
Added:
Provide a method:
Linear table of 10 numbers, random(10)=5, delete node 5
Linear table of 9 numbers, random(9)=2, delete node 2
. . . .
Last random sequence 5,2. . . . .
This feels quite random.
Pseudocode:
<code>生成长度为10的数组a,压入1~10(或其他你想要的数) for (i = a.length - 1; i > 0; i--) { 生成一个0~i的随机数j(0 <= j < i) 交换a[i]和a[j] }</code>
There is no way for a computer to generate a truly random number... It can only try to make the generated numbers evenly distributed in various intervals..
It’s not a problem with the random algorithm, it’s that the sample is too small. If you try 100 random numbers, it will look very random
1, 3, 2, 4, 5, 6, 7, 8, 10, 9 are randomly selected, but you still feel it’s not random enough
You want to hash the ten numbers from 1-10 to ten positions. Just hash it.