除了数组切片之外,还有没有其他方法可以生成在两个数字之间的随机数,而且不会重复直到这两个数字之间的所有数字都被生成?洗牌技术或除了切片之外的任何其他数组方法都将非常有帮助。
除了数组切片之外,还有没有其他方法可以生成在两个数字之间的随机数,而且不会重复直到这两个数字之间的所有数字都被生成?洗牌技术或除了切片之外的任何其他数组方法都将非常有帮助。
首先,我们使用FisherYates实现(感谢@ChristopheD)来随机化JavaScript数组,并扩展了数组原型以使洗牌函数可用。
function arrayShuffle () {
var i = this.length, j, temp;
if ( i === 0 ) return false;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
}
Array.prototype.shuffle =arrayShuffle;
var numbers = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
numbers.shuffle();
pop
方法,我们从种子中获取一个数字,直到它为空。numbers.pop(); //returns a number
start
和 end
范围内的数字填充的数组,我们使用简单的循环来创建我们的种子。var start = 1;
var end = 5;
var numbers = new Array();
for (var i = start; i <= end; i++) {
numbers.push(i);
}
这是一个在jsfiddle上的示例。
更新:使用Fisher-Yates算法使洗牌更有效。
N ** N
个等可能的洗牌,而N
个元素的排列数为N!
,通常情况下N ** N
不是N!
的精确倍数。 - 6502当我处理较小的数组时,通常会通过随机排序数组来处理:
yourArray.sort(function() { return 0.5 - Math.random() });
试试这个 http://jsbin.com/imukuh/1/edit:
function randRange(min, max) {
var result = [];
for (var i=min; i<=max; i++) result.push(i);
return result.map(function(v){ return [Math.random(), v] })
.sort().map(function(v){ return v[1] });
}
console.log(randRange(1,5));
// [4, 3, 1, 5, 2]
// [3, 5, 2, 4, 1]
// [1, 5, 2, 3, 4]
// [3, 2, 5, 1, 4]
// ...
function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }
您可以将您想要随机化的数组传递给shuffle
函数,并返回一个新的已随机排序的数组。 - thefrontender