Added an overload of next_rand_u32() that generates a random number in [0,N) range.

This commit is contained in:
LoRd_MuldeR 2018-10-20 21:05:39 +02:00
parent 88f4dd9cca
commit a61fc10602
2 changed files with 19 additions and 1 deletions

View File

@ -124,7 +124,8 @@ namespace MUtils
* \return The function returns a *random* unsigned 32-Bit value.
*/
MUTILS_API quint32 next_rand_u32(void);
MUTILS_API quint32 next_rand_u32(const quint32 max);
/**
* \brief Generates a *random* unsigned 64-Bit value.
*

View File

@ -122,6 +122,23 @@ quint32 MUtils::next_rand_u32(void)
return rnd;
}
quint32 MUtils::next_rand_u32(const quint32 max)
{
static const uint32_t DIV_LUT[64] =
{
0xFFFFFFFF, 0xFFFFFFFF, 0x80000000, 0x55555556, 0x40000000, 0x33333334, 0x2AAAAAAB, 0x24924925,
0x20000000, 0x1C71C71D, 0x1999999A, 0x1745D175, 0x15555556, 0x13B13B14, 0x12492493, 0x11111112,
0x10000000, 0x0F0F0F10, 0x0E38E38F, 0x0D79435F, 0x0CCCCCCD, 0x0C30C30D, 0x0BA2E8BB, 0x0B21642D,
0x0AAAAAAB, 0x0A3D70A4, 0x09D89D8A, 0x097B425F, 0x0924924A, 0x08D3DCB1, 0x08888889, 0x08421085,
0x08000000, 0x07C1F07D, 0x07878788, 0x07507508, 0x071C71C8, 0x06EB3E46, 0x06BCA1B0, 0x06906907,
0x06666667, 0x063E7064, 0x06186187, 0x05F417D1, 0x05D1745E, 0x05B05B06, 0x0590B217, 0x0572620B,
0x05555556, 0x0539782A, 0x051EB852, 0x05050506, 0x04EC4EC5, 0x04D4873F, 0x04BDA130, 0x04A7904B,
0x04924925, 0x047DC120, 0x0469EE59, 0x0456C798, 0x04444445, 0x04325C54, 0x04210843, 0x04104105
};
return (max < 64) ? (next_rand_u32() / DIV_LUT[max]) : (next_rand_u32() / (UINT32_MAX / max + 1U));
}
quint64 MUtils::next_rand_u64(void)
{
return (quint64(next_rand_u32()) << 32) | quint64(next_rand_u32());