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

前端 未结 12 1623
广开言路
广开言路 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:42

    Interestingly, Microsoft used the same technique in their pick-random-browser-page.

    They used a slightly different comparison function:

    function RandomSort(a,b) {
        return (0.5 - Math.random());
    }
    

    Looks almost the same to me, but it turned out to be not so random...

    So I made some testruns again with the same methodology used in the linked article, and indeed - turned out that the random-sorting-method produced flawed results. New test code here:

    function shuffle(arr) {
      arr.sort(function(a,b) {
        return (0.5 - Math.random());
      });
    }
    
    function shuffle2(arr) {
      arr.sort(function(a,b) {
        return (Math.round(Math.random())-0.5);
      });
    }
    
    function shuffle3(array) {
      var tmp, current, top = array.length;
    
      if(top) while(--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
      }
    
      return array;
    }
    
    var counts = [
      [0,0,0,0,0],
      [0,0,0,0,0],
      [0,0,0,0,0],
      [0,0,0,0,0],
      [0,0,0,0,0]
    ];
    
    var arr;
    for (var i=0; i<100000; i++) {
      arr = [0,1,2,3,4];
      shuffle3(arr);
      arr.forEach(function(x, i){ counts[x][i]++;});
    }
    
    alert(counts.map(function(a){return a.join(", ");}).join("\n"));
    

提交回复
热议问题