在JavaScript中生成特定范围内的随机整数?

在JavaScript中生成特定范围内的随机整数?,javascript,random,integer,Javascript,Random,Integer,如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?页面上有一些示例: 这是背后的逻辑。这是一条简单的三条规则: Math.random()返回一个介于0(包含)和1(排除)之间的数字。我们有一个这样的间隔: [0 .................................... 1) 现在,我们想要一个介于min(包括)和max(不包括)之间的数字: 我们可以使用Math.random获得[min,max]区间内的对应

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

页面上有一些示例:


这是背后的逻辑。这是一条简单的三条规则:

Math.random()
返回一个介于0(包含)和1(排除)之间的
数字。我们有一个这样的间隔:

[0 .................................... 1)
现在,我们想要一个介于
min
(包括)和
max
(不包括)之间的数字:

我们可以使用
Math.random
获得[min,max]区间内的对应值。但是,首先我们应该通过从第二个区间减去
min
来考虑问题:

[0 .................................... 1)
[min - min ............................ max - min)
x = Math.random() * (max - min) + min;
这使得:

[0 .................................... 1)
[0 .................................... max - min)
我们现在可以应用
Math.random
,然后计算相应的数。让我们选择一个随机数:

                Math.random()
                    |
[0 .................................... 1)
[0 .................................... max - min)
                    |
                    x (what we need)
因此,为了找到
x
,我们将:

x = Math.random() * (max - min);
别忘了把
min
加回去,这样我们就可以得到[min,max]间隔内的一个数字:

[0 .................................... 1)
[min - min ............................ max - min)
x = Math.random() * (max - min) + min;
这是MDN中的第一个函数。第二个函数返回一个介于
min
max
之间的整数,两者都包含在内

/*Mthod 1:*/
    var i = 78, j = 247, k = 170, a = [], b = [], c, d, e, f, l = 0;
    for(; i <= j; i++){ a.push(i); }
    while(l < 170){
        c = Math.random()*100; c = Math.floor(c);
        d = Math.random()*100; d = Math.floor(d);
        b.push(a[c]); e = c + d;
        if((b.length != k) && (e < k)){  b.push(a[e]); }
        l = b.length;
    }
    console.log('Method 1:');
    console.log(b);
/*Method 2:*/

    var a, b, c, d = [], l = 0;
    while(l < 170){
        a = Math.random()*100; a = Math.floor(a);
        b = Math.random()*100; b = Math.floor(b);
        c = a + b;
        if(c <= 247 || c >= 78){ d.push(c); }else{ d.push(a); }
        l = d.length;
    }
    console.log('Method 2:');
    console.log(d);
现在,要获取整数,可以使用
round
ceil
floor

您可以使用
Math.round(Math.random()*(max-min))+min
,但这会给出一个非均匀分布。无论是
min
还是
max
都只有大约一半的掷骰机会:

min...min+0.5...min+1...min+1.5   ...    max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘   ← Math.round()
   min          min+1                          max
如果将
max
排除在间隔之外,则其滚动的机会比
min
更少

使用
Math.floor(Math.random()*(max-min+1))+min
可以获得完全均匀的分布

min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
|        |        |         |        |        |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘   ← Math.floor()
   min     min+1               max-1    max

您不能在该等式中使用
ceil()
-1
,因为
max
现在滚动的机会稍小,但您也可以滚动(不需要的)
min-1
结果。

页面上有一些示例:

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

这是它背后的逻辑。这是一条简单的三条规则:

Math.random()
返回一个介于0(包括)和1(不包括)之间的
Number
。因此我们有如下间隔:

[0 .................................... 1)
现在,我们想要一个介于
min
(包括)和
max
(不包括)之间的数字:

我们可以使用
Math.random
获得[min,max]区间内的对应值。但是,首先我们应该通过从第二个区间减去
min
来考虑问题:

[0 .................................... 1)
[min - min ............................ max - min)
x = Math.random() * (max - min) + min;
这使得:

[0 .................................... 1)
[0 .................................... max - min)
我们现在可以应用
Math.random
,然后计算相应的数。让我们选择一个随机数:

                Math.random()
                    |
[0 .................................... 1)
[0 .................................... max - min)
                    |
                    x (what we need)
因此,为了找到
x
,我们将:

x = Math.random() * (max - min);
别忘了把
min
加回去,这样我们就可以得到[min,max]间隔内的一个数字:

[0 .................................... 1)
[min - min ............................ max - min)
x = Math.random() * (max - min) + min;
这是MDN中的第一个函数。第二个函数返回一个介于
min
max
之间的整数,两者都包含在内

/*Mthod 1:*/
    var i = 78, j = 247, k = 170, a = [], b = [], c, d, e, f, l = 0;
    for(; i <= j; i++){ a.push(i); }
    while(l < 170){
        c = Math.random()*100; c = Math.floor(c);
        d = Math.random()*100; d = Math.floor(d);
        b.push(a[c]); e = c + d;
        if((b.length != k) && (e < k)){  b.push(a[e]); }
        l = b.length;
    }
    console.log('Method 1:');
    console.log(b);
/*Method 2:*/

    var a, b, c, d = [], l = 0;
    while(l < 170){
        a = Math.random()*100; a = Math.floor(a);
        b = Math.random()*100; b = Math.floor(b);
        c = a + b;
        if(c <= 247 || c >= 78){ d.push(c); }else{ d.push(a); }
        l = d.length;
    }
    console.log('Method 2:');
    console.log(d);
现在,要获取整数,可以使用
round
ceil
floor

您可以使用
Math.round(Math.random()*(max-min))+min
,但这会给出一个非均匀分布。无论是
min
还是
max
都只有大约一半的掷骰机会:

min...min+0.5...min+1...min+1.5   ...    max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘   ← Math.round()
   min          min+1                          max
如果将
max
排除在间隔之外,则其滚动的机会比
min
更少

使用
Math.floor(Math.random()*(max-min+1))+min
可以获得完全均匀的分布

min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
|        |        |         |        |        |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘   ← Math.floor()
   min     min+1               max-1    max
您不能在该等式中使用
ceil()
-1
,因为
max
现在滚动的机会稍小,但您也可以滚动(不需要的)
min-1
结果

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.
}
Math.random()
返回一个介于0和1之间的随机双精度,如果我们将它乘以1加上
top
bottom
之间的差值,我们将得到一个介于
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
top-bottom
的整数,因此我们现在需要做的就是将
bottom
添加到该结果中,以获得范围
bottom
top
的整数。:D


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

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 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.
}
Math.random()
返回一个介于0和1之间的随机双精度,如果我们将它乘以1加上
top
bottom
之间的差值,我们将得到一个介于
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
top-bottom
的整数,因此我们现在需要做的就是添加
bott
function random(high,low) {
    high++;
    return Math.floor((Math.random())*(high-low))+low;
}
function randomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomNumber(min, max) {
  return Math.random() * (max - min) + min;
}
// 0 -> 10
Math.floor(Math.random() * 11);

// 1 -> 10
Math.floor(Math.random() * 10) + 1;

// 5 -> 20
Math.floor(Math.random() * 16) + 5;

// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
function genRandomNumber(how_many_number,min,max) {

            // parameters
            // how_many_number : how many numbers you want to generate. For example it is 5.
            // min(inclusive) : minimum/low value of a range. it must be any positive integer but less than max. i.e 4
            // max(inclusive) : maximun value of a range. it must be any positive integer. i.e 50
            // return type: array

            var random_number = [];
            for (var i = 0; i < how_many_number; i++) {
                var gen_num = parseInt((Math.random() * (max-min+1)) + min);
                do {
                    var is_exist = random_number.indexOf(gen_num);
                    if (is_exist >= 0) {
                        gen_num = parseInt((Math.random() * (max-min+1)) + min);
                    }
                    else {
                        random_number.push(gen_num);
                        is_exist = -2;
                    }
                }
                while (is_exist > -1);
            }
            document.getElementById('box').innerHTML = random_number;
        }
// get random number within provided base + exponent
// by Goran Biljetina --> 2012

function isEmpty(value){
    return (typeof value === "undefined" || value === null);
}
var numSeq = new Array();
function add(num,seq){
    var toAdd = new Object();
     toAdd.num = num;
     toAdd.seq = seq;
     numSeq[numSeq.length] = toAdd;
}
function fillNumSeq (num,seq){
    var n;
    for(i=0;i<=seq;i++){
        n = Math.pow(num,i);
        add(n,i);
    }
}
function getRandNum(base,exp){
    if (isEmpty(base)){
        console.log("Specify value for base parameter");
    }
    if (isEmpty(exp)){
        console.log("Specify value for exponent parameter");
    }
    fillNumSeq(base,exp);
    var emax;
    var eseq;
    var nseed;
    var nspan;
    emax = (numSeq.length);
    eseq = Math.floor(Math.random()*emax)+1;
    nseed = numSeq[eseq].num;
    nspan = Math.floor((Math.random())*(Math.random()*nseed))+1;
    return Math.floor(Math.random()*nspan)+1;
}

console.log(getRandNum(10,20),numSeq);
//testing:
//getRandNum(-10,20);
//console.log(getRandNum(-10,20),numSeq);
//console.log(numSeq);
    <!DOCTYPE html>
<html>
    <head>
            <meta charset="utf-8" />
    </head>
    <body>
        <script>
            /*

                assuming that window.crypto.getRandomValues is available
                the real range would be fron 0 to 1,998 instead of 0 to 2,000
                See javascript documentation for explanation
                https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
            */
            var array = new Uint8Array(2);
            window.crypto.getRandomValues(array);
            console.log(array[0] + array[1]);

        </script>
    </body>
</html>
Math.floor((Math.random() * max) + min);
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;
}());
        var r = new Random();
        var nextInt = r.Next(1, 100); //returns an integer between range
        var nextDbl = r.NextDouble(); //returns a random decimal
    function genRandom(length)
    {
     const t1 = new Date().getMilliseconds();
     var min = "1",max = "9";
     var result;
     var numLength = length;
     if (numLength != 0)
     {
        for (var i = 1; i < numLength; i++)
        {
           min = min.toString() + "0";
           max = max.toString() + "9";
        }
     } 
     else
     {
        min = 0;
        max = 0;
        return; 
     }

      for (var i = min; i <= max; i++)
      {
           //Empty Loop
      }

      const t2 = new Date().getMilliseconds();
      console.log(t2);
      result = ((max - min)*t1)/t2;
      console.log(result);
      return result;
    }
Math.floor(Math.random() *  max);
var randUpTo = function(num) {
    return Math.floor(Math.random() * (num - 1) + 0);
};
var randBetween = function (min, max) {
    return Math.floor(Math.random() * (max - min - 1)) + min;
};
var randFromTill = function (min, max) {
    return Math.random() * (max - min) + min;
};
var randFromTo = function (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};
function rnd(min,max){
    return Math.floor(Math.random()*(max-min+1)+min );
}
let randomNumber = function(first,second){
let number = Math.floor(Math.random()*Math.floor(second));
while(number<first){

    number = Math.floor(Math.random()*Math.floor(second));
}
return number;
}
Math.floor((Math.random() * 10) % n)
function randomRange(min, max) {
   return Math.floor( (Math.random() * (max-min +1) ) + min );
}