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.
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 callingsafeRand()
below.:This still isn't ideal, but reduces the correlations significantly, as every additional, discarded call to
Math.random()
will.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 :
EDIT : Damn, too late ^^