How to generate two different random numbers?

2019-02-13 10:08发布

I need to generate two different random numbers, they can't be equal to each other or to a third number. I tried to use a lot of if's to cover every possibility but, it seems my algorithm skills are not that good.

Can anyone help me on this?

var numberOne = Math.floor(Math.random() * 4);
var numberTwo = Math.floor(Math.random() * 4);
var numberThree = 3; // This number will not always be 3

if((numberOne == numberThree) && (numberOne + 1 < 3)) {
    numberOne++;
} else if ((numberOne == numberThree) && (numberOne + 1 == 3)) {
    numberOne = 0;
}

if ((numberOne == numberTwo) && (numberOne+1 < 3)) {
    if (numberOne+1 < 3) {
        numberOne++;
    } else if(numberThree != 0) {
        numberOne = 0;
    }
}

This is what I have so far, the next step would be:

if (numberTwo == numberThree) {
    (...)
}

Is my line of thought right? Note: Numbers generated need to be between 0 and 3. Thanks in advance.

8条回答
做个烂人
2楼-- · 2019-02-13 10:34

Be aware that back-to-back calls to Math.random() triggers a bug in chrome as indicated here, so modify any of the other answers by calling safeRand() below.:

function safeRand() {
  Math.random();
  return Math.random();
}

This still isn't ideal, but reduces the correlations significantly, as every additional, discarded call to Math.random() will.

查看更多
Anthone
3楼-- · 2019-02-13 10:35

I'm not sure of what you're trying to do (or actually, why is your code so complicated for what I understood). It might not be the most optimized code ever, but here is my try :

var n3 = 3;
var n2 = Math.floor(Math.random() * 4);
var n1 = Math.floor(Math.random() * 4);

while(n1 == n3)
{
    n1 = Math.floor(Math.random() * 4);
}
while (n2 == n1 || n2 == n3)
{
    n2 = Math.floor(Math.random() * 4);
}

EDIT : Damn, too late ^^

查看更多
登录 后发表回答