I generate many many random numbers that need to be between 1 and 15 (included) in C++. Of course, I can generate zillons of
std::uniform_int_distribution<std::mt19937::result_type> random(1, 15);
but this is a waste since this mersenn twister generates 32 bits (or even 64 using mt19937_64) of random values, and I would only keep 4 bits and throw away all the rest, and in my case, performance is an issue and random number generation is a significant contributor.
My idea was thus to generate for example a single 64-bit random value between 0 and 2^64-1, and select 4 bits among them. The issue is that I can't find a way to have the generated values between 1 and 15. Example:
unsigned long long int r = uniform(generator); // between 0 and 2^64-1
unsigned int r1 = (r+1)&15; // first desired random value
unsigned int r2 = ((r>>4)+1)&15; //second desired random value
unsigned int r3 = ((r>>8)+1)&15; //third desired random value
...
Here, this version of course doesn't work : despite the +1, the generated values are still between 0 and 15 (since if r&15
happens to be 0xb1111
then adding 1 produces the result 0xb0000
).
Also, I would like the distribution to remain uniform (for instance, I wouldn't want to bias the least significant bit to occur more often, which could be the case with something like (r&15+1)|((r&15 +1) >> 4)
since the value 0xb0001
would occur twice often).