我需要对JS中的一组值进行随机化,并且我调用了例如三次随机化函数。我如何才能记住并阻止随机生成器给出它以前给我的结果?我只能给一个值一次。
var value = Math.floor(Math.random() * 11);发布于 2009-08-18 13:06:11
使用memoization模式。
var randomize = (function () {
var memo = [],
maxlen = 10;
return function() {
if (memo.length === maxlen) {
throw new Error('Out of values');
}
var value = Math.floor(Math.random() * (maxlen + 1));
if (memo.indexOf(value) !== -1) {
return randomize();
}
memo.push(value);
return value;
};
}());发布于 2009-08-18 12:55:21
如下所示(经过测试):
Array.prototype.unique = function () {
var r = new Array();
o:for(var i = 0, n = this.length; i < n; i++)
{
for(var x = 0, y = r.length; x < y; x++)
{
if(r[x]==this[i])
{
continue o;
}
}
r[r.length] = this[i];
}
return r;
}
var temp = [];
//keep going until the array size is three
while(temp.length < 3) {
temp.push(Math.floor(Math.random() * 11));
//unique() will remove the dupes thus affecting the length
temp = temp.unique();
}
alert(temp[0] + ' ' + temp[1] + ' ' + temp[2]);发布于 2009-08-18 14:09:08
你更大的目标是什么?如果您正在尝试以随机顺序从有限集中选择项目,那么您将需要考虑使用随机排序算法来随机化排序,然后根据需要以生成的随机顺序删除它们。
https://stackoverflow.com/questions/1293609
复制相似问题