给定一个从 100 到 400 的范围,我怎样才能在这个区间内生成数字,并且它们之间的差异不小于,比如说 20?
因此,这些数字的数组看起来像:[120, 155, 187, ...]
这是我从随机间隔生成数字的函数:
function randomFromInterval(from,to){
return Math.floor(Math.random()*(to-from+1)+from);
}
有任何想法吗?
这是我尝试过的,但这很愚蠢:)
function generateNumbers(){
var nr1 = randomFromInterval(100, xw-100);
var nr1y = randomFromInterval(100, xw-100);
var nr2 = randomFromInterval(100, xw-100);
while (Math.abs(nr1 - nr2) < 20){
nr2 = randomFromInterval(100, xw-100);
}
var nr2y = randomFromInterval(100, xw-100);
var nr3 = randomFromInterval(100, xw-100);
while (Math.abs(nr1 - nr3) < 20 && Math.abs(nr2 - nr3) < 20){
nr3 = randomFromInterval(100, xw-100);
}
var nr3y = randomFromInterval(100, xw-100);
var nr4 = randomFromInterval(100, xw-100);
while (Math.abs(nr1 - nr4) < 20 && Math.abs(nr2 - nr4) < 20 && Math.abs(nr3 - nr4) < 20){
nr4 = randomFromInterval(100, xw-100);
}
var nr4y = randomFromInterval(100, xw-100);
var nr5 = randomFromInterval(100, xw-100);
while (Math.abs(nr1 - nr5) < 20 && Math.abs(nr2 - nr5) < 20 && Math.abs(nr3 - nr5) < 20 && Math.abs(nr4 - nr5) < 20){
nr5 = randomFromInterval(100, xw-100);
}
var nr5y = randomFromInterval(100, xw-100);
var nrArray = [[nr1,nr1y],[nr2,nr2y],[nr3,nr3y],[nr4,nr4y],[nr5,nr5y]];
console.log(nrArray);
return nrArray;
}