javascript - 用有距离的随机整数填充数组
问题描述
我需要一个用随机整数填充的数组这些整数应该彼此非常不同,即每个项目之间必须至少有 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);
}
但总是不成功,包括无限循环......
解决方案
看看这样的事情:
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");
}
推荐阅读
- php - laravel 未定义的偏移量 0
- android-studio - android studio-选择在单选组中按下哪个单选按钮不起作用
- python - 将临床文档名称映射到 LOINC 名称
- django - 保存到 JSONField 时 Django 和 Celery 的意外行为
- html - 是否可以将数据 URL 放入 QR 码中?
- python-3.x - Boto3 Kafka API 未出现
- amazon-web-services - Codedeploy 回滚未选择先前成功的构建版本
- java - 如何在 Spring Boot 中防止外部连接失败(如 Redis 服务器)快速失败?
- rest - REST API 用户资源及其密码
- php - 从控制器获取数据并通过 AJAX 显示