如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?


当前回答

这里有一个函数,它生成一个介于最小值和最大值之间的随机数,两者都包含在内。

const randomInt = (max, min) => Math.round(Math.random() * (max - min)) + min;

其他回答

接受答案的问题

值得注意的是,接受的答案不能正确处理min大于max的情况。下面是一个例子:

min=数学ceil(2);max=数学楼层(1);对于(变量i=0;i<25;i++){console.log(Math.floor(Math.random()*(max-min+1))+min);}

此外,如果你不熟悉这个小算法,阅读起来有点啰嗦和不清楚。

为什么Randojs是更好的解决方案?

Randomjs自动处理最小值大于最大值的情况(并且它是加密安全的):

对于(var i=0;i<25;i++)console.log(rando(2,1));<script src=“https://randojs.com/1.0.0.js“></script>

它还处理负数、零和其他所有你期望的东西。如果您需要执行浮点运算或使用其他变量类型,也有一些选项,但我不会在这里讨论它们。它们在网站上,因此如果需要,您可以深入研究。最后的原因很明显。从风格上看,它更干净,更容易阅读。


TL;医生,给我解决方案。。。

randojs.com使这一点和许多其他常见的随机性变得强大、可靠、简单/可读:

console.log(随机(20,30));<script src=“https://randojs.com/1.0.0.js“></script>

我想用一个例子来解释:

函数在JavaScript中生成5到25范围内的随机整数

概述:(i) 首先将其转换为范围-从0开始。(ii)然后将其转换为所需的范围(然后将非常易于完成)。

所以基本上,如果你想生成从5到25的随机整数,那么:

第一步:将其转换为范围-从0开始

从“max”和“min”中减去“lower/minimum number”。即

(5-5) - (25-5)

因此,范围将为:

0-20 ...正确的

第二步

现在,如果您希望两个数字都包含在范围内,即“0和20”,则公式为:

数学方程式:Math.floor((Math.random()*21))

一般公式:Math.floor((Math.random()*(max min+1)))

现在,如果我们将减去的/最小的数字(即5)添加到范围中,那么我们可以自动获得0到20的范围=>5到25

第三步

现在将减去的差值加在等式(即5)中,并将“Math.floor”添加到整个等式中:

数学方程式:Math.floor((Math.random()*21)+5)

一般公式:Math.floor((Math.random()*(max-min+1))+min)

因此,最终函数将是:

function randomRange(min, max) {
   return Math.floor((Math.random() * (max - min + 1)) + min);
}
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
function getRandomInt(lower, upper)
{
    //to create an even sample distribution
    return Math.floor(lower + (Math.random() * (upper - lower + 1)));

    //to produce an uneven sample distribution
    //return Math.round(lower + (Math.random() * (upper - lower)));

    //to exclude the max value from the possible values
    //return Math.floor(lower + (Math.random() * (upper - lower)));
}

要测试此函数以及此函数的变体,请将以下HTML/JavaScript保存到文件中,然后用浏览器打开。该代码将生成一个图表,显示一百万个函数调用的分布。代码还将记录边缘事例,因此如果函数产生的值大于最大值,或小于最小值,则您将知道大约。

<html>
    <head>
        <script type="text/javascript">
        function getRandomInt(lower, upper)
        {
            //to create an even sample distribution
            return Math.floor(lower + (Math.random() * (upper - lower + 1)));

            //to produce an uneven sample distribution
            //return Math.round(lower + (Math.random() * (upper - lower)));

            //to exclude the max value from the possible values
            //return Math.floor(lower + (Math.random() * (upper - lower)));
        }

        var min = -5;
        var max = 5;

        var array = new Array();

        for(var i = 0; i <= (max - min) + 2; i++) {
          array.push(0);
        }

        for(var i = 0; i < 1000000; i++) {
            var random = getRandomInt(min, max);
            array[random - min + 1]++;
        }

        var maxSample = 0;
        for(var i = 0; i < max - min; i++) {
            maxSample = Math.max(maxSample, array[i]);
        }

        //create a bar graph to show the sample distribution
        var maxHeight = 500;
        for(var i = 0; i <= (max - min) + 2; i++) {
            var sampleHeight = (array[i]/maxSample) * maxHeight;

            document.write('<span style="display:inline-block;color:'+(sampleHeight == 0 ? 'black' : 'white')+';background-color:black;height:'+sampleHeight+'px">&nbsp;[' + (i + min - 1) + ']:&nbsp;'+array[i]+'</span>&nbsp;&nbsp;');
        }
        document.write('<hr/>');
        </script>
    </head>
    <body>

    </body>
</html>

所有这些解决方案都使用了太多的火力。您只需要调用一个函数:Math.random();

Math.random() * max | 0;

这将返回一个介于0(包含)和max(非包含)之间的随机整数。