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.
Generally, in pseudo-code, I do :
This way you'll get two different random numbers. With an additional condition you can make them different to another (3rd) number.
You need to compare
n2
with the minimum ofn1
andn3
first to ensure you do not have an equality:Suppose
n1=1
andn3=2
. If you getn2=1
and compare it first withn3
, you won't increasen2
in the first step. In the second step, you would increase it sincen2 >= n1
. In the end,n2 = 2 = n3
.This algorithm guarantees to have a uniform distribution, and you only call twice
Math.random()
.You can run a
while
loop until all numbers are different.Here is the jsfiddle with the above code based on @jfriend00's suggestion http://jsfiddle.net/x4g4kkwc/1.
Here is the original working demo: http://jsfiddle.net/x4g4kkwc/
This version minimizes the number of calls to random like you did, but is a bit simpler and not biased. In your version, there is a 2/4 chance that numberOne goes to 0, and a 1/4 chance if goes to 1 and 2. In my version there are equal odds of numberOne ending up as 0, 1 or 2).
Its a special case of the array-shuffling version deceze mentioned but for when you have only two numbers
You can create an array of random possibilities and then remove items from that array as they are used, selecting future random numbers from the remaining values in the array. This avoids looping trying to find a value that doesn't match previous items.
Working demo: http://jsfiddle.net/jfriend00/vhy6jxja/
FYI, this technique is generally more efficient than looping until you get something new when you are asking to randomly select most of the numbers within a range because this just eliminates previously used numbers from the random set so it doesn't have to keep guessing over and over until it gets an unused value.