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


当前回答

使用此函数获取给定范围内的随机数:

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

其他回答

其他答案没有考虑到0和1这两个完全合理的参数。相反,您应该使用圆形而不是天花板或地板:

function randomNumber(minimum, maximum){
    return Math.round( Math.random() * (maximum - minimum) + minimum);
}

console.log(randomNumber(0,1));  # 0 1 1 0 1 0
console.log(randomNumber(5,6));  # 5 6 6 5 5 6
console.log(randomNumber(3,-1)); # 1 3 1 -1 -1 -1

Use:

function getRandomizer(bottom, top) {
    return function() {
        return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
    }
}

用法:

var rollDie = getRandomizer( 1, 6 );

var results = ""
for ( var i = 0; i<1000; i++ ) {
    results += rollDie() + " ";    // Make a string filled with 1000 random numbers in the range 1-6.
}

细分:

我们正在返回一个函数(从函数式编程中借用),当调用该函数时,将返回值bottom和top之间的随机整数,包括bottom。我们说“包含”是因为我们希望将底部和顶部都包含在可返回的数字范围内。这样,getRandomizer(1,6)将返回1、2、3、4、5或6。

(“底部”是较低的数字,“顶部”是较大的数字)

Math.random() * ( 1 + top - bottom )

Math.random()返回一个介于0和1之间的随机双精度,如果我们将其乘以1加上顶部和底部之间的差值,我们将得到一个介于介于0和1+b-a之间的双精度。

Math.floor( Math.random() * ( 1 + top - bottom ) )

Math.floor将数字向下舍入到最接近的整数。所以我们现在有了0和上下之间的所有整数。1看起来很令人困惑,但它需要存在,因为我们总是向下舍入,因此没有它就永远无法到达顶部数字。我们生成的随机小数需要在0到(1+上下)的范围内,这样我们就可以向下舍入,得到0到上下的整数:

Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom

上一个示例中的代码为我们提供了一个范围为0和上下的整数,因此我们现在需要做的就是将底部添加到该结果中,以获得范围为底部和顶部(含)的整数D


注意:如果你先传入一个非整数值或更大的数字,你会得到不希望的行为,但除非有人要求,否则我不会深入研究参数检查代码,因为它与原始问题的意图相去甚远。

接受答案的问题

值得注意的是,接受的答案不能正确处理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中Random类的Microsoft.NET实现-

var Random = (function () {
    function Random(Seed) {
        if (!Seed) {
            Seed = this.milliseconds();
        }
        this.SeedArray = [];
        for (var i = 0; i < 56; i++)
            this.SeedArray.push(0);
        var num = (Seed == -2147483648) ? 2147483647 : Math.abs(Seed);
        var num2 = 161803398 - num;
        this.SeedArray[55] = num2;
        var num3 = 1;
        for (var i_1 = 1; i_1 < 55; i_1++) {
            var num4 = 21 * i_1 % 55;
            this.SeedArray[num4] = num3;
            num3 = num2 - num3;
            if (num3 < 0) {
                num3 += 2147483647;
            }
            num2 = this.SeedArray[num4];
        }
        for (var j = 1; j < 5; j++) {
            for (var k = 1; k < 56; k++) {
                this.SeedArray[k] -= this.SeedArray[1 + (k + 30) % 55];
                if (this.SeedArray[k] < 0) {
                    this.SeedArray[k] += 2147483647;
                }
            }
        }
        this.inext = 0;
        this.inextp = 21;
        Seed = 1;
    }

    Random.prototype.milliseconds = function () {
        var str = new Date().valueOf().toString();
        return parseInt(str.substr(str.length - 6));
    };

    Random.prototype.InternalSample = function () {
        var num = this.inext;
        var num2 = this.inextp;
        if (++num >= 56) {
            num = 1;
        }
        if (++num2 >= 56) {
            num2 = 1;
        }
        var num3 = this.SeedArray[num] - this.SeedArray[num2];
        if (num3 == 2147483647) {
            num3--;
        }
        if (num3 < 0) {
            num3 += 2147483647;
        }
        this.SeedArray[num] = num3;
        this.inext = num;
        this.inextp = num2;
        return num3;
    };

    Random.prototype.Sample = function () {
        return this.InternalSample() * 4.6566128752457969E-10;
    };

    Random.prototype.GetSampleForLargeRange = function () {
        var num = this.InternalSample();
        var flag = this.InternalSample() % 2 == 0;
        if (flag) {
            num = -num;
        }
        var num2 = num;
        num2 += 2147483646.0;
        return num2 / 4294967293.0;
    };

    Random.prototype.Next = function (minValue, maxValue) {
        if (!minValue && !maxValue)
            return this.InternalSample();
        var num = maxValue - minValue;
        if (num <= 2147483647) {
            return parseInt((this.Sample() * num + minValue).toFixed(0));
        }
        return this.GetSampleForLargeRange() * num + minValue;
    };

    Random.prototype.NextDouble = function () {
        return this.Sample();
    };

    Random.prototype.NextBytes = function (buffer) {
        for (var i = 0; i < buffer.length; i++) {
            buffer[i] = this.InternalSample() % 256;
        }
    };
    return Random;
}());

Use:

var r = new Random();
var nextInt = r.Next(1, 100); // Returns an integer between range
var nextDbl = r.NextDouble(); // Returns a random decimal

返回1到10之间的随机数:

Math.floor((Math.random()*10) + 1); 

返回1到100之间的随机数:

Math.floor((Math.random()*100) + 1)