用唯一的随机数javascript填充数组

populate array with UNIQUE random numbers javascript

本文关键字:填充 数组 javascript 随机数 唯一      更新时间:2023-09-26

我有一个数组:

var array = new Array();

这是一个随机函数,它给出了一个介于minmax之间的随机数(参见前面的Stackoverflow主题):

function randomIntFromInterval(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

这个数组应该有9个单元格。我想用随机数填充它,重要的条件是每个数字都是唯一的,这意味着这个数组中的一个数字不能被找到两次或两次以上。最后,这里是我被卡住的地方(整个代码):

var array = new Array();
function randomIntFromInterval(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}
// populate the variable "array" with 9 different
// random numbers
function randomlyInitializeArray() {
    var random = 0;
    // For each cell (9 cells) in my "array"
    for (var i = 0; i < maxLength; i++) {
        // Return a number between 1 & 9
        random = randomIntFromInterval(1, maxLength);
        /*  Verifying if this random number is already in 
            the "array" /!' stuck here /!' */
    }
}

那么,用9个唯一(不同)数字填充数组的逻辑是什么呢?

为什么不获取一个从1到-max的数组,然后对其进行洗牌

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o) { //v1.0
  for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
};
function randomIntFromInterval(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
// populate the variable "array" with 9 different
// random numbers
function randomlyInitializeArray(min, max) {
  var start = min;
  var randomMax = randomIntFromInterval(min, max)
  var myArray = [];
  for (var i = 0; start <= randomMax; myArray[i++] = start++);
  myArray = shuffle(myArray);
  console.log("Min: "+min);
  console.log("Max: "+max);
  console.log("random Max: "+randomMax)
  
  console.log(myArray)
}
randomlyInitializeArray(2,40);

如果你想从一个特定的区间获得9个随机数(使用该函数):

你可以使用do-while循环来获得随机数,直到你有了一个唯一的数字。

您可以通过contains()函数检查一个数字是否已经在数组中。

for (var i = 0; i < maxLength; i++) {
    do {
        random = randomIntFromInterval(1, maxLength);
    while( array.contains(random) );          // will return false if random isn't asigned
    array.push(random);
}

如果您不关心间隔,并且只想要9个唯一值(按随机顺序为1-9),则可以使用1-9创建数组,并使用对其进行混洗

var myArray = ['1','2','3','4','5','6','7','8','9'];
newArray = shuffle(myArray);
function shuffle(o){ 
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

shuffle方法取自如何对数组进行shuffle

所以你想要1-9中的9个随机唯一数字?在我看来,这就像想要数字1到9按随机顺序排列一样。

这可以简单地通过:来完成

[1,2,3,4,5,6,7,8,9].sort(function () { // shuffle
    return Math.random() - 0.5; // returns > 0 ~50% of the time
});

否则你可以做一些类似的事情:

var array = [];
while (array.length < 9) {
    array = array_unique(array.concat([ get_random_number() ]);
}
console.log(array);

大多数框架都以这样或那样的方式具有array_unique函数,或者只是编写自己的函数。

有更快的方法可以做到这一点,但明确包含对unique()的调用使该实现易于理解和验证。

我建议使用while循环,类似

function unique_nums(n) {
    var myarray = [];
    for (var i=0;i<n;i++){
        var next_num = Math.random();
        while (myarray.indexOf(next_num) !== -1) {
            next_num = Math.random();
        }
        myarray.push(next_num);
    }
    return myarray;
}

这将确保随机数在push编辑之前不存在于数组中。