如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
下面是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
其他回答
这是我用来生成随机数的方法。
function random(min,max) {
return Math.floor((Math.random())*(max-min+1))+min;
}
Math.random()返回一个介于0(含)和1(不含)之间的数字。我们将这个数字乘以范围(max-min)。这将导致一个介于0(含)和范围之间的数字。
例如,随机(2,5)。我们将随机数0≤x<1乘以范围(5-2=3),因此我们现在有一个数x,其中0≤x<3。
为了强制函数将最大值和最小值都视为包含值,我们在范围计算中添加1:Math.random()*(max-min+1)。现在,我们将随机数乘以(5-2+1=4),得到一个数字x,即0≤x<4。如果我们对这个计算进行下限,我们得到一个整数:0≤x≤3,每个结果的可能性相等(1/4)。
最后,我们需要将其转换为请求值之间的整数。由于我们已经有一个介于0和(max-min)之间的整数,我们可以简单地通过添加最小值将值映射到正确的范围。在我们的示例中,我们将0到3之间的整数加2,得到2到5之间的整数。
使用计算机程序生成随机数后,如果选取的数字是初始数字的一部分或全部,则仍将其视为随机数。但如果它被改变了,数学家就不接受它是一个随机数,他们可以称它为一个有偏数。
但是,如果您正在为一项简单的任务开发一个程序,则不需要考虑这种情况。但是,如果你正在开发一个程序,为有价值的东西(如彩票程序或赌博游戏)生成随机数,那么如果你不考虑上述情况,你的程序将被管理层拒绝。
所以对于这类人,我的建议是:
使用Math.random()生成一个随机数(说这个n):
Now for [0,10) ==> n*10 (i.e. one digit) and for[10,100) ==> n*100 (i.e., two digits) and so on. Here square bracket indicates that the boundary is inclusive and a round bracket indicates the boundary is exclusive.
然后删除小数点后的其余部分。(即,获得发言权)-使用Math.floor()。这可以完成。
如果你知道如何读取随机数表来选择一个随机数,那么你知道上面的过程(乘以1、10、100等)不会违反我在开头提到的过程(因为它只改变小数点的位置)。
研究以下示例,并根据您的需要进行开发。
如果你需要一个样本[0,9],那么n10的下限是你的答案,如果你需要[0,99],那么n100的下限就是你的答案等等。
现在让我们进入您的角色:
您已要求提供特定范围内的数字。(在这种情况下,你在这个范围内是有偏差的。通过掷骰子从[1,6]中取一个数字,那么你就有偏差到[1,6],但当且仅当骰子无偏差时,它仍然是一个随机数。)
所以考虑一下你的范围==>[78,247]范围内的元素数=247-78+1=170;(因为两个边界都包含在内)。
/* Method 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);
注意:在方法一中,首先我创建了一个包含所需数字的数组,然后将它们随机放入另一个数组中。
在方法二中,随机生成数字,并检查这些数字是否在您需要的范围内。然后将其放入数组中。在这里,我生成了两个随机数,并使用它们的总数通过最小化获得有用数字的失败率来最大化程序的速度。然而,将生成的数字相加也会产生一些偏差。所以我推荐我的第一种方法来生成特定范围内的随机数。
在这两种方法中,控制台都会显示结果(在Chrome中按F12打开控制台)。
下面是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
function randomRange(min, max) {
return ~~(Math.random() * (max - min + 1)) + min
}
如果您使用Undercore.js,也可以使用
_.random(min, max)
您可以使用此代码段,
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;
}