Generating unique random numbers (integers) between 0 and 'x'

Math.floor(Math.random() * (limit+1))

Math.random() generates a floating point number between 0 and 1, Math.floor() rounds it down to an integer.

By multiplying it by a number, you effectively make the range 0..number-1. If you wish to generate it in range from num1 to num2, do:

Math.floor(Math.random() * (num2-num1 + 1) + num1)

To generate more numbers, just use a for loop and put results into an array or write them into the document directly.


function generateRange(pCount, pMin, pMax) {
    min = pMin < pMax ? pMin : pMax;
    max = pMax > pMin ? pMax : pMin;
    var resultArr = [], randNumber;
    while ( pCount > 0) {
        randNumber = Math.round(min + Math.random() * (max - min));
        if (resultArr.indexOf(randNumber) == -1) {
            resultArr.push(randNumber);
            pCount--;
        }
    }
    return resultArr;
}

Depending on range needed the method of returning the integer can be changed to: ceil (a,b], round [a,b], floor [a,b), for (a,b) is matter of adding 1 to min with floor.


Use the basic Math methods:

  • Math.random() returns a random number between 0 and 1 (including 0, excluding 1).
  • Multiply this number by the highest desired number (e.g. 10)
  • Round this number downward to its nearest integer

    Math.floor(Math.random()*10) + 1
    

Example:

//Example, including customisable intervals [lower_bound, upper_bound)
var limit = 10,
    amount = 3,
    lower_bound = 1,
    upper_bound = 10,
    unique_random_numbers = [];

if (amount > limit) limit = amount; //Infinite loop if you want more unique
                                    //Natural numbers than exist in a
                                    // given range
while (unique_random_numbers.length < limit) {
    var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
    if (unique_random_numbers.indexOf(random_number) == -1) { 
        // Yay! new random number
        unique_random_numbers.push( random_number );
    }
}
// unique_random_numbers is an array containing 3 unique numbers in the given range