Skip to content Skip to sidebar Skip to footer

A Random Number Between 1 And 4 That's Not Another Random Number

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.floor(Math.random()*4+1)){

Solution 1:

How about a while loop instead? Initialise a2 = a1 and then:

while(a2 == a1) {
    a2 = Math.floor(Math.random() * 4 + 1);
}

Solution 2:

The logic of your test is inverted. For loops continue to execute while the test is true, not if it fails. Rather than: a2 != a1 && a2 != 0 you should have (a2 == a1) || (a2 == 0). Though also keep in mind that the alert will also only be executed in that case when a2 is an invalid state, though an alert following the for should be valid.

Or if you're looking for the fun math-y way to do it using modular arithmetic (no retries necessary):

a2 = (Math.floor(Math.random() * 3 + (a1 + 1)) % 4) || 4

Solution 3:

Try with this function. It'll give you an array with numbers from 1 to max in random order. Then you can use it to assign a value to a variable and it'll never repeat:

Edit: I found a purely functional way to do it:

functionrandomRange(min, max) {
  return (newArray(++max-min))
    .join('.').split('.')
    .map(function(v,i){ return min+i })
    .sort(function(){ return0|Math.random()*max });
}

console.log(rand(1,4)); //-> [4,2,1,3] random array from 1 to 4var arr = rand(1,4);
var a = arr[0];
var b = arr[1];
...

Edit 2: Seems like the above has problems with some browsers, check out Random but just in Chrome for a better solution.

Demo:http://jsbin.com/ohohum/1/edit (run multiple times to see the randomness)

Solution 4:

Just add one if the number is greater than or equal to the one you want to exclude:

var a2 = Math.floor(Math.random() * 3 + 1);

if(a2 >= a1) {
    a2++;
}

Solution 5:

You are choosing a new a2 value when a2 is not the same as a1 or zero. This is backwards - you set a2 to zero before the loop, so it never executes.

You need to loop while a2 is either zero, or equal to a1:

var a1 = Math.floor(Math.random()*4+1); 

//Answer2for(a2 = 0; a2 == a1 || a2 == 0; a2 = Math.floor(Math.random()*4+1)){
    // nothing here
}   
alert(a2);

Post a Comment for "A Random Number Between 1 And 4 That's Not Another Random Number"