简体   繁体   English

如何从随机位生成范围内的整数

[英]How to generate integers within a range from random bits

I have a source of random bits that I would like to massage into integers of various sizes, roughly correlating with the size of popular dice (1-4, 1-6, etc.)我有一个随机位源,我想将其按摩成各种大小的整数,与流行骰子的大小(1-4、1-6 等)大致相关

The code I am writing is PHP, so a response in that language is ideal.我正在编写的代码是 PHP,因此使用该语言的响应是理想的。 However, an algorithmic generic response would be totally fine as well.但是,算法通用响应也完全可以。

I would prefer an answer more sophisticated than simply seeding PHP's random() function with chunks of my random data.我更喜欢一个更复杂的答案,而不是简单地用我的随机数据块播种 PHP 的 random() function。

If you have an arbitrary number of bits available, you might choose to use a rejection method, along the lines of Java's Random.nextInt(int) .如果您有任意数量的可用位,您可能会选择使用拒绝方法,类似于 Java 的Random.nextInt(int) The pseudocode taken from there is:从那里获取的伪代码是:

public int nextInt(int n) {
     if (n<=0)
         new IllegalArgumentException("n must be positive");

     if ((n & -n) == n)  // i.e., n is a power of 2
         return (int)((n * (long)next(31)) >> 31);

     int bits, val;
     do {
         bits = next(31);
         val = bits % n;
     } while(bits - val + (n-1) < 0);
     return val;
 }

next() is a function that returns a specified number of random bits, concatenated into an int . next()是一个 function ,它返回指定数量的随机位,连接成一个int You could replace this with your random bit source.你可以用你的随机位源替换它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM