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


当前回答

我在W3Schools上找到了这个简单的方法:

Math.floor((Math.random() * max) + min);

其他回答

接受答案的问题

值得注意的是,接受的答案不能正确处理min大于max的情况。下面是一个例子:

min=数学ceil(2);max=数学楼层(1);对于(变量i=0;i<25;i++){console.log(Math.floor(Math.random()*(max-min+1))+min);}

此外,如果你不熟悉这个小算法,阅读起来有点啰嗦和不清楚。

为什么Randojs是更好的解决方案?

Randomjs自动处理最小值大于最大值的情况(并且它是加密安全的):

对于(var i=0;i<25;i++)console.log(rando(2,1));<script src=“https://randojs.com/1.0.0.js“></script>

它还处理负数、零和其他所有你期望的东西。如果您需要执行浮点运算或使用其他变量类型,也有一些选项,但我不会在这里讨论它们。它们在网站上,因此如果需要,您可以深入研究。最后的原因很明显。从风格上看,它更干净,更容易阅读。


TL;医生,给我解决方案。。。

randojs.com使这一点和许多其他常见的随机性变得强大、可靠、简单/可读:

console.log(随机(20,30));<script src=“https://randojs.com/1.0.0.js“></script>

我想,这是所有贡献中最简单的。

maxNum = 8,
minNum = 4

console.log(Math.floor(Math.random() * (maxNum - minNum) + minNum))

console.log(Math.floor(Math.random() * (8 - 4) + 4))

这将在控制台中记录4到8之间的随机数,包括4到8。

我在W3Schools上找到了这个简单的方法:

Math.floor((Math.random() * max) + min);

使用现代JavaScript+Lodash:

const generateRandomNumbers = (max, amount) => {
  const numbers = [...Array(max).keys()];
  const randomNumbers = sampleSize(numbers, amount);

  return randomNumbers.sort((a, b) => a - b);
};

此外,TypeScript版本:

const generateRandomNumbers = (max: number, amount: number) => {
  const numbers = [...Array(max).keys()];
  const randomNumbers: number[] = sampleSize(numbers, amount);

  return randomNumbers.sort((a: number, b: number) => a - b);
};

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的结果。