用有距离的随机整数填充数组 [英] Fill an array with distanced random integers

查看:289
本文介绍了用有距离的随机整数填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need an array to be filled with random integers Those integers should be very distinct from each other i.e. must at least be 20 units of separation between each items

这是我到目前为止尝试过的:

This is what i have tried so far :

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

但总是失败,包括无限循环...

but always unsuccessful, including infinite loops...

推荐答案

看一下这样的东西:

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");
}

这篇关于用有距离的随机整数填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆