可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
You can run a while
loop until all numbers are different.
// All numbers are equal
var numberOne = 3;
var numberTwo = 3;
var numberThree = 3;
// run this loop until numberOne is different than numberThree
do {
numberOne = Math.floor(Math.random() * 4);
} while(numberOne === numberThree);
// run this loop until numberTwo is different than numberThree and numberOne
do {
numberTwo = Math.floor(Math.random() * 4);
} while(numberTwo === numberThree || numberTwo === numberOne);
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/
回答2:
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.
function makeRandoms(notThis) {
var randoms = [0,1,2,3];
// faster way to remove an array item when you don't care about array order
function removeArrayItem(i) {
var val = randoms.pop();
if (i < randoms.length) {
randoms[i] = val;
}
}
function makeRandom() {
var rand = randoms[Math.floor(Math.random() * randoms.length)];
removeArrayItem(rand);
return rand;
}
// remove the notThis item from the array
if (notThis < randoms.length) {
removeArrayItem(notThis);
}
return {r1: makeRandom(), r2: makeRandom()};
}
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.
回答3:
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).
i0 = Math.floor(Math.random() * 4); //one of the 4 numbers in [0, 4), namely 3
i1 = Math.floor(Math.random() * 3); //only 3 possibilities left now
i2 = Math.floor(Math.random() * 2); //only two possibilities left now
x0 = i0;
x1 = i1 + (i1 >= i0 ? 1 : 0);
x2 = i2 + (i2 >= i0 ? 1 : 0) + (i2 >= i1 : 1 : 0);
Its a special case of the array-shuffling version deceze mentioned but for when you have only two numbers
回答4:
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 ^^
回答5:
var rangeTo = 4;
var uniqueID = (function () {
var id, cache = [];
return function () {
id = Math.floor((Math.random() * (new Date).getTime()) % rangeTo);
var cacheLength = cache.length;
if (cacheLength === rangeTo) {
throw new Error("max random error");
};
var i = 0
while (i < cacheLength) {
if (cache[i] === id) {
i = 0;
id = Math.floor((Math.random() * (new Date).getTime()) % rangeTo);
}
else {
i++;
}
}
cache.push(id);
return id;
};
})();
回答6:
var n = 4; //to get two random numbers between 0 and 3
var n3 = 2; //for example
var n1 = Math.floor(Math.random(n-1));
var n2 = Math.floor(Math.random(n-2));
if(n1 >= n3) {
n1++;
if(n2 >= n3)
n2++;
if(n2 >= n1)
n2++;
} else {
if(n2 >= n1)
n2++;
if(n2 >= n3)
n2++;
}
You need to compare n2
with the minimum of n1
and n3
first to ensure you do not have an equality:
Suppose n1=1
and n3=2
. If you get n2=1
and compare it first with n3
, you won't increase n2
in the first step. In the second step, you would increase it since n2 >= n1
. In the end, n2 = 2 = n3
.
This algorithm guarantees to have a uniform distribution, and you only call twice Math.random()
.
回答7:
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.
回答8:
Generally, in pseudo-code, I do :
var nbr1 = random()
var nbr2 = random()
while (nbr1 == nbr2) {
nbr2 = random();
}
This way you'll get two different random numbers.
With an additional condition you can make them different to another (3rd) number.