PDA

View Full Version : js random shuffle no duplicates | proof of concept



maclenin
December 26th, 2012, 03:51 PM
Using javascript, I wanted to (randomly) shuffle a sequential set of numbers (e.g. 1 to x) and then insert the entire shuffled set into a web-based grid. This seems to facilitate the job (while eliminating duplicates):

var rNDM=[]; //target array for shuffled unique set.
var DrNDM=[]; //'optional' array for duplicates.
var rNG=25; //largest number in set (i.e. shuffle numbers 1 through 25).

while (rNDM.length<rNG) { //loop until target array contains a full set of shuffled unique numbers.
rnd=Math.floor((Math.random()*rNG)+1); //generate a random number between (and including) 1 and the largest number in your defined set (e.g. 25).
if (rNDM.length===0) {//if the target array is empty...
rNDM.push(rnd);} //...add the random number to the target array.
else { //else (if) the target array already contains at least one number...
if (rNDM.indexOf(rnd) === -1) { //...verify that the random number just generated does NOT already exist in the target array.
rNDM.push(rnd);} //if the random number does NOT exist in the target array, add the random number to the target array.
else {//optional (perhaps) - if the random number DOES already exist in the target array...
DrNDM.push(rnd);} //...send the random number, instead, to the duplicates array.
}} //close.

console.log(rNDM); //...does it work?

Read here: Fisher-Yates (http://sedition.com/perl/javascript-fy.html)
Tested here: jsBin (http://jsbin.com/#javascript,html,live)

Thanks for any thoughts.

P.S. Will mull non-sequential set shuffles, as well.