JavaScript 生成除某些值外的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27406377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:27:10  来源:igfitidea点击:

JavaScript generate random number except some values

javascript

提问by DevEx

I'm generating random numbers from 1 to 20 by calling generateRandom(). How can I exclude some values, say 8 and 15?

我通过调用生成从 1 到 20 的随机数generateRandom()。如何排除某些值,例如 8 和 15?

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

var test = generateRandom(1, 20)

回答by Anas Jame

it should be orinstead of and

它应该是代替

function generateRandom(min, max) {
    var num = Math.floor(Math.random() * (max - min + 1)) + min;
    return (num === 8 || num === 15) ? generateRandom(min, max) : num;
}

var test = generateRandom(1, 20)

回答by Bathsheba

One way, which will maintain the generator's statistical properties, is to generate a number in [1, 18]. Then apply, in this order:

一种保持生成器统计特性的方法是在 [1, 18] 中生成一个数字。然后按以下顺序申请:

  1. If the number is 8 or more, add 1.

  2. If the number is 15 or more, add 1.

  1. 如果数字为 8 或更多,则加 1。

  2. 如果数字为 15 或更多,则加 1。

I'd be reluctant to reject and re-sample as that can cause correlation plains to appear in linear congruential generators.

我不愿意拒绝和重新采样,因为这会导致相关平原出现在线性同余生成器中。

回答by Juan Saravia

Right now I'm using this and it works without causing browser issues with infinities loops, also tested in mobile devices (using Ionic/Cordova):

现在我正在使用它,它不会导致浏览器出现无穷循环问题,也在移动设备中进行了测试(使用 Ionic/Cordova):

function getRandomIndex(usedIndexs, maxIndex) {
    var result = 0;
    var min = 0;
    var max = maxIndex - 1;
    var index = Math.floor(Math.random()*(max-min+1)+min);

    while(usedIndexs.indexOf(index) > -1) {
        if (index < max) {
            index++;
        } else {
          index = 0;
        }
    }

    return index;
}

回答by James Harrington

Here is a slightly modified answer that is similar to all the others but it allows your to pass a single or an array of failing numbers

这是一个稍微修改的答案,与所有其他答案相似,但它允许您传递单个或一组失败的数字

function generateRandom(min, max, failOn) {
    failOn = Array.isArray(failOn) ? failOn : [failOn]
    var num = Math.floor(Math.random() * (max - min + 1)) + min;
    return failOn.includes(num) ? generateRandom(min, max, failOn) : num;
}

回答by Felype

I've read through all these answers and they differ a lot in philosophy, so I thought I might add my very own 2 bits, despite of this question having an answer, because I do think there is a better and more elegant way of approaching this problem.

我已经阅读了所有这些答案,它们在哲学上有很大不同,所以我想我可以添加我自己的 2 位,尽管这个问题有答案,因为我确实认为有一种更好、更优雅的方法来解决这个问题。

We can make a function that takes min, max and blacklist as parameters and outputs a random result without using recursion (and with close to 0 if statements):

我们可以制作一个函数,将 min、max 和 blacklist 作为参数并输出随机结果,而不使用递归(并且使用接近 0 的 if 语句):

const blrand = function(min, max, blacklist) { if(!blacklist) blacklist = [] let rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; let retv = 0; while(blacklist.indexOf(retv = rand(min,max)) > -1) { } return retv; }

const blrand = function(min, max, blacklist) { if(!blacklist) blacklist = [] let rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; let retv = 0; while(blacklist.indexOf(retv = rand(min,max)) > -1) { } return retv; }

usage: let randomNumber = blrand(0, 20, [8, 15]);

用法: let randomNumber = blrand(0, 20, [8, 15]);

回答by Onk_r

You can simply do like this

你可以简单地这样做

function generatedRandExclude(showed,max) {
     let randNo = -1;
     while(showed.length < max) {
         randNo = Math.floor(Math.random() * Math.floor(max)); 
          if(!showed.includes(randNo)) {
             showed.push(randNo);
              break;
          }
     }
     return randNo;
}

let showed = [];
function run() {
    console.log(generatedRandExclude(showed,6));
}
run();
run();
run();
run();

generatedRandExclude generate random number excluded using array showed.

generateRandExclude 生成使用 array 排除的随机数showed

回答by Jacobo Lopez

This is a simple and neat idea, I am a electromechanical engineer and I am just learning JS. This is going to print a random numeber between 1 and 100. Except 8 and 15

这是一个简单而巧妙的想法,我是一名机电工程师,我只是在学习 JS。这将打印 1 到 100 之间的随机数。除了 8 和 15

 var r;   // this is the random integer.
 var val; //this will serve as validator for the random integer.

 val=0; 
 while(val==0)    {
 r=Math.round(Math.random()*100)+1;
 if(r!=8 && r!=15){val=1;}    //a valid number will be any number different from 8 and 15
                              //then validator will change and go out from the loop.
                }   
document.write(r);

回答by Amit Joki

You could make use of a recursive function

您可以使用递归函数

function generateRandom(min, max, num1, num2) {
    var rtn = Math.floor(Math.random() * (max - min + 1)) + min;
    return rtn == num1 || rtn == num2 ? generateRandom(min, max, num1, num2) : rtn;
}

回答by Adem

I think it should be like this, if you want good distribution on all numbers. and, for this solution, it is required to higher max than 15 and lower min that 8

我认为应该是这样,如果你想在所有数字上都有良好的分布。并且,对于此解决方案,要求最大值高于 15,最小值低于 8

function generateRandom(min, max) {
    var v =  Math.floor(Math.random() * (max - min + 1 - 2)) + min;
    if (v == 8) return max-1;
    else if (v == 15) return max-2;
    else return v;
}

var test = generateRandom(1, 20)

回答by sareed

You can build an array dynamically. Depending on where you are getting the excluded numbers. Something like:

您可以动态构建数组。取决于您在哪里获得排除的数字。就像是:

var excluded = [8, 15];
var random = [];
for(var i = min; i <= max; i++) {
  if(excluded.indexOf(i) !== -1) {
    random.push(i);
  }
}

Then use the tips found in the answer for this post: How can I generate a random number within a range but exclude some?. Should get you to where you want to go.

然后使用在这篇文章的答案中找到的提示:如何在一个范围内生成一个随机数但排除一些?. 应该带你去你想去的地方。