gpt4 book ai didi

javascript - 生成 0 到 'x' 之间的唯一随机数(整数)

转载 作者:IT王子 更新时间:2023-10-29 03:03:10 26 4
gpt4 key购买 nike

我需要生成一组唯一(无重复)整数,并且介于 0 和给定数字之间。

即:

var limit = 10;
var amount = 3;

如何使用 Javascript 生成 3 个介于 1 和 10 之间的唯一数字?

最佳答案

使用基本的数学方法:

  • Math.random() 返回一个介于 0 和 1 之间的随机数(包括 0,不包括 1)。
  • 将此数字乘以所需的最高数字(例如 10)
  • 将此数字向下舍入到最接近的整数

    Math.floor(Math.random()*10) + 1

例子:

//Example, including customisable intervals [lower_bound, upper_bound)
var limit = 10,
amount = 3,
lower_bound = 1,
upper_bound = 10,
unique_random_numbers = [];

if (amount > limit) limit = amount; //Infinite loop if you want more unique
//Natural numbers than exist in a
// given range
while (unique_random_numbers.length < limit) {
var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
if (unique_random_numbers.indexOf(random_number) == -1) {
// Yay! new random number
unique_random_numbers.push( random_number );
}
}
// unique_random_numbers is an array containing 3 unique numbers in the given range

关于javascript - 生成 0 到 'x' 之间的唯一随机数(整数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8378870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com