java - 用数组中最后元素覆盖随机抽取到的位置,这样的算法真的合适么?
怪我咯
怪我咯 2017-04-17 15:29:09
0
1
488
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
Ty80

This is an algorithm that takes a random value inside an array and then changes its position. Every time a random number is taken from the array, the random number is replaced with the value at the end of the array, so that all the values ​​taken are moved to the end of the array. The new random value will be between 0 and n-1, that is, from the head to the last untransposed position, so there will be no duplicate values.
For example:
numbers = [0,1,2,3,4,5],
If r=2, take out a random value numbers[2], which is the number 2,
and then transpose, numbers[r] = numbers[n - 1], 2 is swapped to the last digit of the array, and the array becomes:
[0,1,5,3,4,2],
5 is swapped to the front, this After n--, when the random value is taken again, it is taken from [0,1,5,3,4,2] (bold part), so the new random value will definitely not contain The 2 that has been taken out.
In the same way, when the value is retrieved again, this value will be placed in the second to last position.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!