开发者

How to generate integers within a range from random bits

开发者 https://www.devze.com 2023-03-08 00:11 出处:网络
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.)

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.)

T开发者_开发技巧he code I am writing is PHP, so a response in that language is ideal. 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.


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). 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. You could replace this with your random bit source.

0

精彩评论

暂无评论...
验证码 换一张
取 消