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


当前回答

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>

其他回答

接受答案的问题

值得注意的是,接受的答案不能正确处理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>

要获得一个介于1和6之间的随机数,首先执行以下操作:

0.5 + (Math.random() * ((6 - 1) + 1))

这会将一个随机数乘以6,然后再加上0.5。接下来,通过以下操作将该数舍入为正整数:

Math.round(0.5 + (Math.random() * ((6 - 1) + 1))

这将数字四舍五入到最接近的整数。

或者为了更容易理解,请执行以下操作:

var value = 0.5 + (Math.random() * ((6 - 1) + 1))
var roll = Math.round(value);
return roll;

通常,使用变量执行此操作的代码为:

var value = (Min - 0.5) + (Math.random() * ((Max - Min) + 1))
var roll = Math.round(value);
return roll;

从最小值中减去0.5的原因是,仅使用最小值可以获得比最大值多1的整数。通过从最小值中减去0.5,基本上防止了最大值被舍入。

为了获得最佳性能,您只需使用:

var r = (Math.random() * (maximum - minimum + 1) ) << 0

以下是排字的解决方案

function getRandomInt(min:number, max:number):number {
    return min+Math.round(Math.random() * (max-min));
  }

  for(let i:number=0; i<100; i++){
  console.log(`${i+1} >> ${getRandomInt(1,6)}`)

  }

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

Math.random() * max | 0;

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