首页 > 解决方案 > 用有距离的随机整数填充数组

问题描述

我需要一个用随机整数填充的数组这些整数应该彼此非常不同,即每个项目之间必须至少有 20 个单位的间隔

这是我迄今为止尝试过的:

var all = [];
var i = 0;

randomDiff();

function randomDiff() {
    var num1 = randomNumber(10, 290); //chose a first random num in the range...
    all[0] = num1; //...put it in first index of array
    do // until you have 12 items...
    {
        var temp = randomNumber(10, 290); //...you pick a temporary num              
        var j;
        for (j = 0; j < all.length; j++) // for each item already in the array
        {
            if ((temp < all[i] - 10) || (temp > all[i] + 10)) // if the temporary num is different enough                                                            from others members...
            {
                all.push(temp); //then you can store it
                i++; //increment until....
                console.log(all[i]);
            }
        }
    }
    while (i < 11) // ...it is filled with 12 items in array    
}
////////////Radom in int range function///////////////////////////////////////
function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

但总是不成功,包括无限循环......

标签: javascriptarraysrandom

解决方案


看看这样的事情:

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

const LIST_SIZE = 20;
const DISTANCE = 10;

const STOP_AFTER_ATTEMPT = 2000;
const randomList = [];

let attempt = 0;
while(randomList.length < LIST_SIZE && attempt < STOP_AFTER_ATTEMPT) {

  const num = randomNumber(10, 290);

  const numberExistsWithSmallerDistance = randomList.some(r => Math.abs(r - num) < DISTANCE)

  if (!numberExistsWithSmallerDistance) {
    randomList.push(num);
  }

  attempt++;
}
if (randomList.length === LIST_SIZE) {
    console.log(randomList);
} else {
    console.log("Failed to create array with distnct values after ", attempt, " tries");
}

推荐阅读