生成指定范围内的随机整数

生成指定范围内的随机整数

首先来看一下 Math.random 吧,它随机生成一个 0 (包含) ~ 1 (不包含) 之间的浮点数。

基于此,我们可以实现一个函数来生成指定范围内的随机整数(MDN上的例子):

1
2
3
4
5
6
7
8
9
10
11
12
// 用于理解版
const getRandomInt = (min, max) => {
const unit = Math.random();
const range = max - min + 1;
const offset = min;

return Math.floor(unit * range + offset);
}

// 实用精简版
const getRandomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1) + min);

技巧是 range 多加个1,然后再用 Math.floor 给向下取整。unit * range + offset 随机生成的是一个包含最小值但不包含最大值+1的浮点数,再向下取整就是一个既包含最小值又包含最大值的整数了,可谓是非常巧妙了。

这样生成的随机整数各整数被生成到的概率也是相等的,我们做个测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
const probabilities = Array(11).fill(0);

// 随机生成一百万个1-10之间的整数
Array(1_000_000).fill().forEach(() => probabilities[getRandomInt(1, 10)]++);

console.log(probabilities);
// 结果:
// [
// 0, 99883, 99720,
// 99900, 100143, 99933,
// 100150, 99721, 100453,
// 99823, 100274
// ]

每个整数被生成到的概率都是10万左右,所以通过这种方式生成的随机整数也是等概率随机生成。