如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
Mozilla开发者网络页面上有一些示例:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
这是背后的逻辑。这是一个简单的三条规则:
Math.random()返回一个介于0(含)和1(不含)之间的数字。所以我们有一个这样的间隔:
[0 .................................... 1)
现在,我们需要一个介于min(含)和max(不含)之间的数字:
[0 .................................... 1)
[min .................................. max)
我们可以使用Math.random获取[min,max)区间的对应值。但是,首先我们应该通过从第二个区间减去min来稍微考虑一下问题:
[0 .................................... 1)
[min - min ............................ max - 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加回来,这样我们就可以得到[分钟,最大值]间隔内的数字:
x = Math.random() * (max - min) + min;
这是MDN的第一个函数。第二个,返回一个介于min和max之间的整数,两者都包含在内。
现在,对于整数,可以使用round、ceil或floor。
您可以使用Math.round(Math.random()*(max-min))+min,但这给出了一个非偶数分布。最小值和最大值都只有大约一半的掷骰机会:
min...min+0.5...min+1...min+1.5 ... max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max
如果将最大值排除在区间之外,那么它比最小值滚动的机会更小。
使用Math.floor(Math.random()*(max-min+1))+min,您可以获得完全均匀的分布。
min... min+1... ... max-1... max.... (max+1 is excluded from interval)
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max
你不能在这个等式中使用ceil()和-1,因为max现在的掷骰机会稍微少了一些,但你也可以掷(不需要的)min-1的结果。
其他回答
使用以下代码,您可以在给定范围内生成一个随机数数组,而无需重复。
function genRandomNumber(how_many_numbers, min, max) {
// Parameters
//
// how_many_numbers: 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): Maximum 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_numbers; 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;
}
我在W3Schools上找到了这个简单的方法:
Math.floor((Math.random() * max) + 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
以下是排字的解决方案
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)}`)
}
// Example
function ourRandomRange(ourMin, ourMax) {
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}
ourRandomRange(1, 9);
// Only change code below this line.
function randomRange(myMin, myMax) {
var a = Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
return a; // Change this line
}
// Change these values to test your function
var myRandom = randomRange(5, 15);
推荐文章
- 转换php数组到Javascript
- 如何跳转到浏览器页面的顶部
- 在电子邮件消息中是否支持JavaScript ?
- 如何在JavaScript中指定Math.log()的基?
- 多重左赋值JavaScript
- 如何在单个测试基础上更改模拟实现?
- VueJS有条件地为元素添加属性
- Uncaught TypeError:(中间值)(…)不是一个函数
- 如何设置URL查询参数在Vue与Vue路由器
- 无法读取属性“addEventListener”为空
- 如何防止moment.js从webpack加载地区?
- getMonth在javascript中给出前一个月
- 如何在禁用按钮上启用引导工具提示?
- Node.js全局变量
- 在前一个函数完成后调用另一个函数