【发布时间】:2020-05-29 10:17:35
【问题描述】:
我需要一个用随机整数填充的数组 这些整数应该彼此非常不同,即每个项目之间必须至少有 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);
}
但总是不成功,包括无限循环……
【问题讨论】:
-
您能否详细说明“必须至少有 20 个分隔单位”是什么意思?您需要列表中每个给定的数字对 x, y 为 |x - y| >= 20 ?
-
@antoniom ,数组中的所有项目都不能有一个更接近 10 个点的下邻居,也不能有一个最接近 10 个单位的上邻居,因为我对数学不满意这里是一个绘图 [链接]。@ 987654321@
标签: javascript arrays random