3

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

I need to randomly generate a new number between 1-3 but it must not be the same as the last one.

It happens in a loop hundreds of times.

What is the most efficient way of doing this?

7
  • 1
    is it between 1-3, are we talking whole numbers? so options are 1, 2 or 3? Commented Apr 17, 2012 at 10:26
  • 2
    You realise that generating a number from 1-3 without repeating is a) not random and b) functionally equivalent to selecting one of two numbers, i.e. probability 0.5? Commented Apr 17, 2012 at 10:26
  • 1
    ok i understand b) but why a)? Commented Apr 17, 2012 at 10:28
  • What have you tried so far? The efficiency of the loop depends on many things: Are you using this random in the loop only, should it be passed forward as an argument etc. Commented Apr 17, 2012 at 10:39
  • @Moshe because for it to be truly random, each number would have to be independent of the last. As you have the condition that there must be no repeats, the future numbers are affected by the past. Commented Apr 17, 2012 at 10:41

6 Answers 6

5

May the powers 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 a function call, you can inline the code.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, I did exactly the same inline :)
2

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

I've created an array containing 1,2,3 and first I select any number and swap it with the last element. Then I only pick elements from position 0 and 1, and swap them with last element.

Comments

1
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;

Comments

0

You can randomly generate numbers with the random number generator built in to javascript. You need to use Math.random().

If you're push()-ing into an array, you can always check if the previously inserted one is the same number, thus you regenerate the number. Here is an example:

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);
    }
}

Comments

0

As Widor commented generating such a number is equivalent to generating a number with probability 0.5. So you can try something like this (not tested):

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++;
}

Comments

0

The code is tested and it does for what you are after.

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();

2 Comments

Why was this downvoted? It's pretty good and not using array like all the others.
This did not work for me, it did not produce a new random number every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.