且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

随机数的Javascript算法

更新时间:2023-02-26 17:17:15

Math.random()返回0(含)和1(独占)之间的随机数,有一点技巧,你可以有

Math.random() returns a random number between 0 (inclusive) and 1 (exclusive), with a bit of trick, you can have
Math.random()*12+1



将返回1(含)和13(独家)之间的随机数。

这样,那里无需检查是否出现0.

由于您重复使用相同的代码生成多个随机数,因此请将此代码放在函数中以便更好地重复使用代码,例如


that will return a random number between 1 (inclusive) and 13 (exclusive).
In this way, there is no need to check for the occurrence of 0.
Since you are re-using the same code to generate multiple random numbers, put this code in a function for better code re-use, e.g.

function getRndNumb(){
  return Math.floor(Math.random()*12+1);
}



最后,要在重复时重复生成随机数,请使用循环,在这种情况下执行...虽然更合适,例如


Lastly, to repeatedly re-generate random numbers when there is duplication, use a loop, in this case do...while is more appropriate, e.g.

do {
   numb1 = getRndNumb();
   numb2 = getRndNumb();
   numb3 = getRndNumb();
} while (numb1 == numb2 || numb1==numb3 || numb2==numb3)



我会留给你把这些作品放在一起。


I shall leave it to you to put together these pieces.


而不是只检查一次数字,在一个循环中检查它们

循环播放JavaScript时[ ^ ]



例如你可以做这样的事情(注意 - 未经测试)

Rather than just checking the numbers once, check them in a while loop
JavaScript while Loop[^]

e.g. you could do something like this (Note - untested)
while (numb1 == numb2 || numb2 == numb3 || numb1 == numb3 || numb1 == 0 || numb2 == 0 || numb3 == 0){
    if(numb1 == 0 || numb1 == numb2 || numb1 == numb3){
        numb1 = numb1 + 1;
    if(numb2 == 0 || numb2 == numb3 || numb2 == numb3){
        numb2 = numb2 + 1;
    if(numb3 == 0 || numb3 == numb1 || numb3 == numb2){
        numb3 = numb3 + 1;
}