javascript - Decrease the probability of getting random item from array same as previous one -


say, i've got array like

var arr = [1,2,3,4,5,6,7,8,9,10,11,12]; 

and wanna random array item, later re-randomize current item. efficient way exclude or reduce chance of getting same item once again?

does stuff help:

current != arr[math.floor(math.random() * 12)] ? current = arr[math.floor(math.random() * 12)] : arr[math.floor(math.random() * 12)]; 

i mean, recalculate random array index each time or link same value? better way?

if can keep array unsorted: (if not, can use array contains indices of elements in first array)

var array = [ ... ]; var len = array.length;  function getrandomitem(){     if (len <= 0) len = array.length;     var item = math.floor(math.random()*len--);     var x = array[item];     array[item] = array[len];     array[len] = x;     return array[len]; } 

idea behind exclude dispatched items placing them outside of item fetching range. function getrandomitem() not return same item twice until other elements returned.


following modification prevent function return same element returned during previous call, requested.

var array = [ 3, 1, 4, 5, 9, 2, 6, 8, 7 ];  var len = array.length-1;    function getrandomitem(){      if (len == 0) return array[0];      var item = math.floor(math.random()*len);      var x = array[item];      array[item] = array[len];      array[len] = x;      return array[len];  }    document.write("starting array: " + array + "<br/>");  document.write("selected value: " + getrandomitem() + "<br/>");  document.write("resulting array: " + array);

also see fisher–yates shuffle


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -