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
Can you use the Array.sort() function to shuffle an array – Yes.
Are the results random enough – No.
Consider the following code snippet:
var array = ["a", "b", "c", "d", "e"];
var stats = {};
array.forEach(function(v) {
stats[v] = Array(array.length).fill(0);
});
//stats = {
// a: [0, 0, 0, ...]
// b: [0, 0, 0, ...]
// c: [0, 0, 0, ...]
// ...
// ...
//}
var i, clone;
for (i = 0; i < 100; i++) {
clone = array.slice(0);
clone.sort(function() {
return Math.random() - 0.5;
});
clone.forEach(function(v, i) {
stats[v][i]++;
});
}
Object.keys(stats).forEach(function(v, i) {
console.log(v + ": [" + stats[v].join(", ") + "]");
})
Sample output:
a [29, 38, 20, 6, 7]
b [29, 33, 22, 11, 5]
c [17, 14, 32, 17, 20]
d [16, 9, 17, 35, 23]
e [ 9, 6, 9, 31, 45]
Ideally, the counts should be evenly distributed (for the above example, all counts should be around 20). But they are not. Apparently, the distribution depends on what sorting algorithm is implemented by the browser and how it iterates the array items for sorting.
More insight is provided in this article:
Array.sort() should not be used to shuffle an array