简体   繁体   English

javascript中两个限制之间的随机非重复数生成

[英]Random non-repeating number generation in javascript between two limits

Is there any method apart from array splicing that I can use to generate a random number between two numbers without repeating at all until all the numbers between those two numbers have been generated? 除了数组拼接之外,还有什么方法可以用来在两个数字之间生成一个随机数而不重复,直到生成了这两个数之间的所有数字? Shuffling techniques or any other array methods apart from splicing would be extremely helpful. 除了拼接之外,改组技术或任何其他阵列方法将非常有用。

First we use the fisherYates implementation (credit goes to @ChristopheD) and extend the array prototype to have a shuffle function available 首先我们使用fisherYates实现(信用转到@ChristopheD)并扩展数组原型以具有可用的shuffle功能

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();

Now with the use of the pop method we get a number from our seed until it is empty 现在使用pop方法,我们从种子中获取一个数字,直到它为空

numbers.pop(); //returns a number

To make sure we have an array filled with numbers in the range of start and end we use a simple loop to create our seed. 为了确保我们有一个数组填充了startend范围内的数字,我们使用一个简单的循环来创建我们的种子。

var start = 1;
var end = 5;
var numbers = new Array();
for (var i = start; i <= end; i++) {
    numbers.push(i);
}

here is a sample on jsfiddle 这是jsfiddle上的一个示例

UPDATE: put fisherYates algo to shuffle more efficient 更新:让渔民改变洗牌更有效率

处理较小数组时我通常做的是随机排序数组:

yourArray.sort(function() { return 0.5 - Math.random() });

Try this http://jsbin.com/imukuh/1/edit : 试试这个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]
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM