Skip to content Skip to sidebar Skip to footer

Unique Random Number Generation Using Javascript

I use the following code for generating the random number from 0 to 15. I use a function random() for generating the unique number i call the function like this cat=random(); I sa

Solution 1:

I'd create an array and shuffle it using Fisher-Yates.

functionshuffle(arr) {
    var shuffled = arr.slice(0), i = arr.length, temp, index;
    while (i--) {
        index = Math.floor(i * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled;
}

// Create the arrayvar i = 16, arr = [];
while (i--) arr[i] = i;

// Shuffle it
arr = shuffle(arr);

// Array is now the numbers 0-15 in a random orderconsole.log(arr);

Solution 2:

Bored, quick hack job, but I believe it'll work:

// Minimum random numbervar min = 0;

// Maximum random numbervar max = 15;

// Returns a random number between min and maxfunctionrandom() {
    var random_number = Math.random();

    returnMath.floor((random_number * max) + min);
}

// Returns false if number is in the arrayfunctionrandom_is_unique(random_num_, array_) {
    // Could use indexOf, but just looping here for simplicity.// And not so sure IE has this capability.for(i = 0; i < array_.length; i++) {
        if(array_[i] == random_num_) {
            returnfalse;
        }                        
    }
    returntrue;
}

// Returns a guaranteed unique, or -1 if no more unique values// are availble to returnfunctionguaranteed_unique(array_) {
    random_number = random();

    // Just an iterator, so we have a terminating condition
    tries = 0;    

    while(!random_is_unique(random_number, array_)) {
        // This is dumb. There's likely a better way to do this, but it's// quick and dirty. It also does not guarantee you've tested all// integers. if(tries > max) {
            return -1;
        }

        random_number = random();

        tries++;
    }

    return random_number;
}

my_array = newArray();
my_array[0] = 1;
my_array[1] = 15;
my_array[2] = 6;
my_array[3] = 9;
my_array[4] = 13;

my_random_number = guaranteed_unique(my_array);

alert("Random number is " + my_random_number);

Solution 3:

i modified a solution that was useful fr me it gets rid of empty entries between numbers and fills them with unique number between 1-9

var arr = [,2,,4,,6,7,,]; //**example**<br/>while(arr.length < 9){<br/>var randomnumber=Math.floor(Math.random()*9+1);<br/>var found=false;<br/>for(var i=0;i<arr.length;i++){<br/>if(arr[i]==randomnumber){found=true;break;}<br/>
}<br/>
if(!found)<br/>
for(k=0;k<9;k++)<br/>
{if(!arr[k]) //**if it's empty !!MODIFICATION**<br/>
{arr[k]=randomnumber; break;}}<br/>
}<br/>
alert(arr); //**outputs on the screen**<br/>

Post a Comment for "Unique Random Number Generation Using Javascript"