Posted By

devnull69 on 02/20/12


Tagged

javascript array shuffle bias biased


Versions (?)

Array shuffle without bias


 / Published in: JavaScript
 

The usual way to shuffle an array uses the .sort() method with Math.round(Math.random())-0.5 This solution is highly biased based on the sort algorithm used by the browsers. A sort comparison operation has to fulfill the condition "if a>b then b<a" for two consecutive calculations which won't work with this. So here is a possible unbiased solution for a .shuffle() method

  1. // (C) Stephen "felgall" http://www.codingforums.com/showthread.php?t=252059
  2.  
  3. Array.prototype.shuffle = function() {
  4. var s = [];
  5. while (this.length) s.push(this.splice(Math.random() * this.length, 1));
  6. while (s.length) this.push(s.pop());
  7. return this;
  8. }

Report this snippet  

You need to login to post a comment.