How to generate two different random numbers?

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/


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.