For some reason the following code doesn\'t work.
var a1 = Math.floor(Math.random()*4+1);
//Answer2
for(a2 = 0; a2 != a1 && a2 != 0; a2 = Math.floo
There are two standard ways of doing this kind of thing. I'm considering a slightly more general framework though
Create the array of base values to select from
var values = [1,2,3,4]
Remove the values you're not interested in
values = Array.filter( values, function(x) { return x!=a1; } )
Select a value at random from the list
var a2 = values[Math.floor(Math.random()*values.length)];
Create the array of values to select
var values = [1,2,3,4]
Select a value at random and retry until it succeeds
var a2 = values[Math.floor(Math.random()*values.length)];
while( a2==a1 )
{
a2 = values[Math.floor(Math.random()*values.length)];
}
If we consider n
to be the length of the initial list and m
to be the number of elements removed, then the filtered version does n
comparisons to build the filtered list of length n-m
, but only one random number generation. In comparison the rejection method does on average n/(n-m)
comparisons and random number generations.