Re: [ js ] chrome 的 Math.random() 好固定的感覺
上面原因有人解釋過了
這裡提供一個簡單的解法:
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/
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.33.238.141
※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1498483294.A.097.html
推
06/26 21:38, , 1F
06/26 21:38, 1F
→
06/26 21:39, , 2F
06/26 21:39, 2F
→
06/26 21:39, , 3F
06/26 21:39, 3F
→
06/26 21:40, , 4F
06/26 21:40, 4F
→
06/26 21:40, , 5F
06/26 21:40, 5F
→
06/26 21:41, , 6F
06/26 21:41, 6F
→
06/26 21:42, , 7F
06/26 21:42, 7F
→
06/26 21:43, , 8F
06/26 21:43, 8F
推
06/27 10:15, , 9F
06/27 10:15, 9F
→
06/27 10:15, , 10F
06/27 10:15, 10F
→
06/27 10:16, , 11F
06/27 10:16, 11F
→
06/27 10:16, , 12F
06/27 10:16, 12F
→
06/27 15:04, , 13F
06/27 15:04, 13F
→
06/28 00:00, , 14F
06/28 00:00, 14F
推
06/28 13:57, , 15F
06/28 13:57, 15F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 3 之 4 篇):
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章