简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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