How to generate integers ranging from random bits

I have a source of random bits that I would like to massage into integers of different sizes, roughly correlating with the size of popular cubes (1-4, 1-6, etc.).

The code I'm writing is PHP, so the answer in this language is perfect. However, the algorithmic general answer will also be completely fine.

I would prefer the answer to be more complex than just carving out the PHP random () function with chunks of my random data.

+3
source share
1 answer

If you have an arbitrary number of bits available, you can use the Java line reject method Random.nextInt(int). Pseudo-code selected from it:

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() - , , int. .

+4

All Articles