Dac*_*che 0 javascript random shuffle
可能重复:
如何随机化一个javascript数组?
我正在用JavaScript编写一个代码,我需要在其中获取35个输入值,在数组中为每个输入值分配一个位置,然后对它们进行洗牌,使它们以不同的顺序重新排列.因此:
var sort = new Array(35);
sort[0] = document.getElementById("d1p1").value;
sort[1] = document.getElementById("d1p2").value;
// ...
// ... (till 35)
var rand1 = Math.floor(Math.random() * 35);
var rand2 = Math.floor(Math.random() * 35);
// ...
// ... (till 35)
var rsort = new Array(35);
rsort[rand1] = document.getElementById("d1p1").value;
rsort[rand2] = document.getElementById("d1p2").value;
Run Code Online (Sandbox Code Playgroud)
唯一的问题是,因为Math.floor(Math.random()*35)从1-35多次生成一些相同的数字(好吧,我猜这是随机点),那么有时会分配两个值相同的输入框,它们返回undefined.有任何想法吗?
为了在随机排列中生成均匀的值分布,您应该做的是这样做:
这是一个潜在的实施:
// first make a copy of the original sort array
var rsort = new Array(sort.length);
for(var idx = 0; idx < sort.length; idx++)
{
rsort[idx] = sort[idx];
}
// then proceed to shuffle the rsort array
for(var idx = 0; idx < rsort.length; idx++)
{
var swpIdx = idx + Math.floor(Math.random() * (rsort.length - idx));
// now swap elements at idx and swpIdx
var tmp = rsort[idx];
rsort[idx] = rsort[swpIdx];
rsort[swpIdx] = tmp;
}
// here rsort[] will have been randomly shuffled (permuted)
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助.