如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
返回1到10之间的随机数:
Math.floor((Math.random()*10) + 1);
返回1到100之间的随机数:
Math.floor((Math.random()*100) + 1)
其他回答
要获得一个介于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,基本上防止了最大值被舍入。
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"> [' + (i + min - 1) + ']: '+array[i]+'</span> ');
}
document.write('<hr/>');
</script>
</head>
<body>
</body>
</html>
一个名为randUpTo的函数,它接受一个数字并返回一个介于0和该数字之间的随机整数:
var randUpTo = function(num) {
return Math.floor(Math.random() * (num - 1) + 0);
};
一个名为randBetween的函数,它接受表示一个范围的两个数字,并返回这两个数字之间的随机整数:
var randBetween = function (min, max) {
return Math.floor(Math.random() * (max - min - 1)) + min;
};
一个名为randFromTill的函数,它接受表示范围的两个数字,并返回一个介于min(含)和max(不含)之间的随机数
var randFromTill = function (min, max) {
return Math.random() * (max - min) + min;
};
一个名为randFromTo的函数,接受表示范围的两个数字,并返回一个介于min(含)和max(含)之间的随机整数:
var randFromTo = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
使用计算机程序生成随机数后,如果选取的数字是初始数字的一部分或全部,则仍将其视为随机数。但如果它被改变了,数学家就不接受它是一个随机数,他们可以称它为一个有偏数。
但是,如果您正在为一项简单的任务开发一个程序,则不需要考虑这种情况。但是,如果你正在开发一个程序,为有价值的东西(如彩票程序或赌博游戏)生成随机数,那么如果你不考虑上述情况,你的程序将被管理层拒绝。
所以对于这类人,我的建议是:
使用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打开控制台)。
Use:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
/*
Assuming that window.crypto.getRandomValues
is available, the real range would be from
0 to 1,998 instead of 0 to 2,000.
See the JavaScript documentation
for an 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>
Uint8Array创建一个最多三位数的数组,最大值为999。这段代码很短。