DEV Community

Discussion on: An algorithm for picking random numbers in a range without repetition

Collapse
 
dllmusic profile image
dllmusic

This works...

//Array to get non repetitive random elements from
var colors = ["Blue", "Red", "Green" , "Yellow", "Orange", "Gray"];
var colorsindx = []; //Indexes (to shuffle)
var randomcolors = []; //Shuffled Array

//init indexes (or push colors.length if adding elements to colors)
for (i=0; i < colors.length; i++) colorsindx.push(i);

//get unique random element and add it to shuffled Array
for (i=0;i < colors.length; i++) {
var rr = Math.floor(Math.random() * (colors.length - i));
var pickedcolor = colors[colorsindx[rr]]; //unique random element
colorsindx.splice(rr,1); //remove picked item index
randomcolors.push(pickedcolor); //push to Shuffled Array
}