上面原因有人解释过了
这里提供一个简单的解法:
Array(N)
.fill()
.map( (v,i) => [ ++i, Math.random() ] )
.sort( (a,b) => a[1] - b[1] )
.map( (x) => x[0] )
写成白话文(?)的话大概是这样
var arr = [];
for (var i = 0; i < N; ++i) {
arr[i] = [ i + 1, Math.random() ];
}
arr.sort(function compare(a, b) {
return a[1] - b[1];
});
for (i = 0; i < N; ++i) {
arr[i] = arr[i][0];
}
如果要用已经填好资料的阵列来做的话可以这样:
// dataArray contains some elements
dataArray
.map( (e) => [e, Math.random()] )
.sort( (a, b) => a[1] - b[1] )
.map( (e) => e[0] )
翻成白话文:
for (var i = 0; i < dataArray.length; ++i) {
dataArray[i] = [ dataArray[i], Math.random() ];
}
dataArray.sort(function compare(a, b) {
return a[1] - b[1];
}
for (i = 0; i < dataArray.length; ++i) {
dataArray[i] = dataArray[i][0];
}
原解法作者:Dominic Wu
讨论串:https://www.facebook.com/groups/f2e.tw/permalink/1326307397406622/