Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  56] [ 5]  / answers: 1 / hits: 113132  / 13 Years ago, sun, december 4, 2011, 12:00:00

I need to generate a set of unique (no duplicate) integers, and between 0 and a given number.



That is:



var limit = 10;
var amount = 3;


How can I use Javascript to generate 3 unique numbers between 1 and 10?


More From » random

 Answers
25

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

[#88753] Friday, December 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annalise

Total Points: 210
Total Questions: 94
Total Answers: 102

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
;