Unique random number in Javascript

Get Unique random numbers


In order to get unique random numbers in array. First we need to get random number using (Math.random()*parseInt(max)).toFixed(0);.
We have the push the value into an array...
For getting second random number we need to get random number and then we have to check whether the number is exist in the array or not. If it is not in the array then we can push it into the array.
Here the code

numbers = new Array("0");
var new_number;
for(j=0;j<6;j++) {
new_numbers = unique_rand(numbers,6);
numbers.push(new_numbers);
}
//Now we have unique random numbers in array 'number'
function get_rand(max) {
var number=(Math.random()*parseInt(max)).toFixed(0);
while (number < 1 ) { //Number Should not equlas to 0
number=(Math.random()*parseInt(max)).toFixed(0);
}
return (number);
}
function unique_rand(list,max) {
var number = get_rand(max);//Get a random number from 1 to 9
var a=0;
for(a=0;a<list.length;a++) {
if(list[a] == number) { //If number already Present
number = get_rand(max);a=-1; //Get a new Number and start it again

}
}
return number;
}



Related Topic The List of Most Popular Blog Widgets
Shuffle Array in JavaScript Randomly
Android: Java Class to Save Bluetooth Receiving File Info
Javascript Date Object Constructor with Examples
Checkbox.onclick() Handler

nScraps.com 2011   Privacy Policy  Terms of Service  Feedback