问题描述
例如,我想在1到2之间生成5个唯一数字. 10.结果应该是1到10之间的5个数字(例如2 3 4 8 10).
For example I would like to generate 5 unique numbers between 1 & 10. The results should be 5 numbers from 1 to 10(for example 2 3 4 8 10).
推荐答案
- 用您的值范围填充数组
- 随机排列数组
- 选择前5个元素
如果范围非常大,并且所需的值数量很小(例如5个不同的值,范围为1 ... 1000000),则可以尝试生成该范围内的随机数并丢弃(不太可能)重复直到您拥有5.继续尝试"方法的问题在于,您花很少的时间花费大量时间使用一串随机值,这些随机值会给您带来很多重复.对于很大范围的值,除非该软件向创伤患者或其他东西提供氧气,否则不太可能值得冒险.
If the range is very large, and the number of values you want is pretty small (like, 5 distinct values in the range 1 ... 1000000) then you can try generating random numbers in the range and throw away (unlikely) duplicates until you have 5. The problem with the "keep trying" approach is that there's a teeny tiny chance you could spend a lot of time with a string of random values that give you a lot of duplicates. For a big range of values, that's so unlikely that it's probably worth risking it unless the software is giving oxygen to trauma patients or something.
这篇关于如何在JavaScript中Y和Z的范围之间随机生成X个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!