我需要生成一个范围在 2 到 5 之间的随机数,每次都不同。例如,我不想连续出现两个 3,或者连续出现两个 5。然后我必须将其输入 for() 循环,如下所示:
for(var i = 0; i < noBoxes.length; i+=randNumber) {
//....
}
我该如何去做呢?
最佳答案
生成一个最大为 n-1 的随机数,并将其添加到原始范围的模中(因为最小值不为 0,所以进行移位):
i = some random int from 2 to 5
delta = randInt(3) // range of possible values from 2 to 5 is 4, minus 1 to
// prevent getting all the way round to i again
nextval = (i-2+delta)%4+2 // shift i down by the minimum, add the
// delta and modulo the range
这是有效的,因为它加起来比范围低 1,所以它永远无法回到原始数字。例如i=3,随机int 0到2,所以最大值为(i-2+2)%3+2=3%3+2=0+2=2。
function differentRandInt(min,max,current) {
var shiftedcurrent = current-min;
var range = max-min+1;
var delta = Math.floor((Math.random()*(range-1))+1);
return (shiftedcurrent + delta)%range + min;
}
因此,如果 i=3,则 i-min 为 1,添加 delta 后的范围为 2,3,4,模 4 得到 2,3,0,因此添加 min 得到 4,5,2。
关于javascript - 产生每次都不同的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10534879/