[英]Fisher–Yates Shuffle table rows
I intend to use the Fisher-Yates shuffle to shuffle existing rows of a given table such as: 我打算使用Fisher-Yates随机播放来随机播放给定表的现有行,例如:
<table>
<tbody id="parent">
<tr id="node1">
<td>1</td>
<td>A</td>
</tr>
<tr id="node2">
<td>2</td>
<td>B</td>
</tr>
<tr id="node3">
<td>3</td>
<td>C</td>
</tr>
<tr id="node4">
<td>4</td>
<td>D</td>
</tr>
<tr id="node5">
<td>5</td>
<td>E</td>
</tr>
<tr id="node6">
<td>6</td>
<td>F</td>
</tr>
</tbody>
</table>
With some help of JQuery, I have the following: 在JQuery的帮助下,我有以下几点:
var parent = $("#parent");
function shuffleRows(parent) {
var rows = parent.children();
for (var i = rows.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = rows[i];
rows.eq(i - 1).after(rows[j]);
rows.eq(j - 1).after(temp);
}
}
shuffleRows(parent);
A working example is here: http://jsfiddle.net/98q9S/ 一个有效的示例在这里: http : //jsfiddle.net/98q9S/
However, as I test the above, I can't help but notice that row A
gets the top spot far more often than other rows, and sometimes two consecutive shuffle produces the exact sequence of rows. 但是,当我测试上面的内容时,我不禁注意到
A
行比其他行更经常获得首位,有时连续两次随机播放会产生确切的行顺序。
I wonder if there is anything wrong in my implementation, or it is just that my sample size is too small. 我想知道我的实现中是否有任何问题,还是仅仅是样本量太小。
I noticed something similar in a toy app I was making using the algorithm. 我在使用该算法制作的玩具应用中注意到了类似的情况。 I ended up going with another solution I found on this site.
我最终找到了在此站点上找到的另一种解决方案。 I hope it helps:
希望对您有所帮助:
makeArrRandom = function(array) {
var counter = array.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.