Most efficient array shuffler

前端 未结 4 1792
自闭症患者
自闭症患者 2020-12-07 02:42

How can I shuffle an array\'s values in the most efficient manner possible?

Each element is just a string containing HTML.

4条回答
  •  自闭症患者
    2020-12-07 02:55

    This is the one I use. It gives a random number to each element, sorts the array by those random numbers (moving the real values along) and then removes the random numbers again. It seems to be equally distributed, but I've not mathematically proven it yet.

    arr = arr.map(function(v) {
        return [v, Math.random()];
    }).sort(function(a, b) {
        return a[1] - b[1];
    }).map(function(v) {
        return v[0];
    });
    

    http://jsfiddle.net/XQRFt/ - Test results (might be slow)

提交回复
热议问题