Javascript - generate a new random number

I have a variable that has a number between 1-3.

I need to randomly create a new number between 1-3, but it should not coincide with the last.

This happens in a cycle hundreds of times.

What is the most efficient way to do this?

+3
source share
6 answers

Let the power of modular arithmetic help you!

This function does what you want using the modulo operator:

/**
 * generate(1) will produce 2 or 3 with probablity .5
 * generate(2) will produce 1 or 3 with probablity .5
 * ... you get the idea.
 */
function generate(nb) {
    rnd = Math.round(Math.random())
    return 1 + (nb + rnd) % 3
}

If you want to avoid calling the function, you can insert the code.

+5
source

Here is the jsFiddle that solves your problem: http://jsfiddle.net/AsMWG/

, 1,2,3, . 0 1 .

+2
var x = 1; // or 2 or 3
// this generates a new x out of [1,2,3] which is != x
x = (Math.floor(2*Math.random())+x) % 3 + 1;
+1

, javascript. Math.random().

push() - , , , . :

var randomArr = [];
var count = 100;
var max = 3;
var min = 1;

while (randomArr.length < count) {
    var r = Math.floor(Math.random() * (max - min) + min);

    if (randomArr.length == 0) {
        // start condition
        randomArr.push(r); 
    } else if (randomArr[randomArr.length-1] !== r) { 
        // if the previous value is not the same 
        // then push that value into the array
        randomArr.push(r);
    }
}
0

, , .

var RandomNumber = {

    lastSelected: 0,

    generate: function() {

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

        if(random == this.lastSelected) {
            generateNumber();
        }
        else {
            this.lastSelected = random;
            return random;
        }
    }
}


RandomNumber.generate();
0

, 0,5. - ( ):

var x; /* your starting number: 1,2 or 3 */
var y = Math.round(Math.random()); /* generates 0 or 1 */

var i = 0;
var res = i+1;
while (i < y) {
   res = i+1;
   i++;
   if (i+1 == x) i++;
}
0

All Articles