在JavaScript中生成特定范围内的随机整数?

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


#1楼

对于具有范围的随机整数,请尝试:

function random(minimum, maximum) {
  var bool = true;

  while (bool) {
    var number = (Math.floor(Math.random() * maximum + 1) + minimum);
    if (number > 20) {
      bool = true;
    } else {
      bool = false;
    }
  }

  return number;
}

#2楼

function randomRange(min, max) {
  return ~~(Math.random() * (max - min + 1)) + min
}

如果您使用的是Underscore.js ,则可以选择使用

_.random(min, max)

#3楼

使用计算机程序生成随机数后,如果所选择的数字是初始数字的一部分或全部,则仍将其视为随机数字。 但是,如果更改了它,则数学家不会将其视为随机数,他们可以称其为有偏数。 但是,如果您正在为一个简单的任务开发程序,则不会考虑这种情况。 但是,如果您正在开发一个程序来为诸如彩票程序或赌博游戏之类的有价值的东西生成一个随机数,那么如果您不考虑上述情况,那么您的程序将被管理层拒绝。

因此,对于那些人,这是我的建议:

使用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 squire bracket indicates that boundary is inclusive and round bracket indicates boundary is exclusive.
Then remove the rest after the decimal point. (i.e. get floor) - using Math.floor(), this can be done.

如果您知道如何读取随机数表以选择一个随机数,则可以知道上面的过程(乘以1,10,100等等)并没有违反我在开始时提到的过程。(因为它只会改变小数点的位置。)

研究以下示例,并根据需要进行开发。

如果需要样本[0,9],则答案为n * 10,如果需要[0,99],则答案为n * 100,依此类推。

现在让我们进入您的角色:

您已问过特定范围内的数字。 (在这种情况下,您在该范围内有偏差。-通过掷骰子从[1,6]中取一个数字,然后将您偏差到[1,6],但当且仅当骰子无偏差时,它仍然是随机的)

因此,请考虑您的范围==> [78,247]范围内的元素数= 247-78 + 1 = 170; (因为两个边界都是包容性的。

/*Mthod 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键打开控制台)


#4楼

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( Math.random()之间的Number 。 所以我们有一个这样的间隔:

[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 ,这样我们就可以在[min,max)间隔中得到一个数字:

x = Math.random() * (max - min) + min;

这是MDN的第一个功能。 第二个,返回介于minmax之间(包括两个端点)的整数。

现在要获取整数,可以使用roundceilfloor

您可以使用Math.round(Math.random() * (max - min)) + min ,但这会产生不均匀的分布。 minmax滚动率只有大约一半:

min...min+0.5...min+1...min+1.5   ...    max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘   ← Math.round()
   min          min+1                          max

如果从间隔中排除了max ,则滚动的机会比min还要少。

使用Math.floor(Math.random() * (max - min +1)) + min您可以获得完美的均匀分布。

min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
|        |        |         |        |        |
└───┬───┘└───┬───┘└─── 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值