Is it correct to use JavaScript Array.sort() method for shuffling?

前端 未结 12 1620
广开言路
广开言路 2020-11-22 03:48

I was helping somebody out with his JavaScript code and my eyes were caught by a section that looked like that:

function randOrd(){
  return (Math.round(Math         


        
12条回答
  •  伪装坚强ぢ
    2020-11-22 04:41

    I have placed a simple test page on my website showing the bias of your current browser versus other popular browsers using different methods to shuffle. It shows the terrible bias of just using Math.random()-0.5, another 'random' shuffle that isn't biased, and the Fisher-Yates method mentioned above.

    You can see that on some browsers there is as high as a 50% chance that certain elements will not change place at all during the 'shuffle'!

    Note: you can make the implementation of the Fisher-Yates shuffle by @Christoph slightly faster for Safari by changing the code to:

    function shuffle(array) {
      for (var tmp, cur, top=array.length; top--;){
        cur = (Math.random() * (top + 1)) << 0;
        tmp = array[cur]; array[cur] = array[top]; array[top] = tmp;
      }
      return array;
    }
    

    Test results: http://jsperf.com/optimized-fisher-yates

提交回复
热议问题