我写了这个功能。它使用生成的数字的历史记录保留其自己的数组,防止初始重复,如果范围内的所有数字均已输出一次,则继续输出随机数:
// Generates a unique number from a range// keeps track of generated numbers in a history array// if all numbers in the range have been returned once, keep outputting random numbers within the rangevar UniqueRandom = { NumHistory: new Array(), generate: function(maxNum) { var current = Math.round(Math.random()*(maxNum-1)); if (maxNum > 1 && this.NumHistory.length > 0) { if (this.NumHistory.length != maxNum) { while($.inArray(current, this.NumHistory) != -1) { current = Math.round(Math.random()*(maxNum-1)); } this.NumHistory.push(current); return current; } else { //unique numbers done, continue outputting random numbers, or we could reset the history array (NumHistory = [];) return current; } } else { //first time only this.NumHistory.push(current); return current; } }};
我希望这对某人有用!
编辑:正如下面的Pointy所指出的,它在大范围内可能会变慢,在0-1000的范围内运行,似乎运行良好)。然而我并不需要很大的范围,所以如果您希望生成并跟踪很大的范围,则此功能可能确实不适合。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)