How to get a unique random integer in a certain range for every number in that range in javascript? -


i have:

function getrandomint(min, max){         return math.floor(math.random() * (max - min + 1)) + min; } 

but problem want randomise population of elements in array (so not appear in same order every time in thing populating) need ensure number returned unique compared other numbers far.

so instead of:

   for(var = 0; < myarray.length; i++) {     } 

i have:

var i; var count = 0; while(count < myarray.length){   count++;   = getrandomint(0, myarray.length); // todo ensure value unique    // stuff myarray[i]; } 

it looks rather independent uniform random numbers rather want random permutation of set {1, 2, 3, ..., n}. think there's shuffle method arrays you.


as requested, here's code example:

function shuffle(array) {   var top = array.length;   while (top--) {       var current = math.floor(math.random() * top);       var tmp = array[current];       array[current] = array[top - 1];       array[top - 1] = tmp;     }   return array; } 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -