| 1 |
#ifndef RANDOM_HH |
| 2 |
#define RANDOM_HH |
| 3 |
|
| 4 |
#include <random> |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
[[nodiscard]] inline auto& global_urng() |
| 9 |
{ |
| 10 |
static std::minstd_rand0 u; |
| 11 |
return u; |
| 12 |
} |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
inline void randomize() |
| 17 |
{ |
| 18 |
static std::random_device rd; |
| 19 |
global_urng().seed(rd()); |
| 20 |
} |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
[[nodiscard]] inline bool random_bool() |
| 25 |
{ |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
auto& generator = global_urng(); |
| 30 |
return generator() & 1; |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
[[nodiscard]] inline int random_int(int from, int thru) |
| 39 |
{ |
| 40 |
static std::uniform_int_distribution<int> d; |
| 41 |
using parm_t = decltype(d)::param_type; |
| 42 |
return d(global_urng(), parm_t{from, thru}); |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
[[nodiscard]] inline float random_float(float from, float upto) |
| 51 |
{ |
| 52 |
static std::uniform_real_distribution<float> d; |
| 53 |
using parm_t = decltype(d)::param_type; |
| 54 |
return d(global_urng(), parm_t{from, upto}); |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
[[nodiscard]] inline uint32_t random_32bit() |
| 68 |
{ |
| 69 |
static std::uniform_int_distribution<uint32_t> d; |
| 70 |
using parm_t = decltype(d)::param_type; |
| 71 |
return d(global_urng(), parm_t{0, 0xffffffff}); |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
template<uint64_t SEED> |
| 84 |
struct PCG |
| 85 |
{ |
| 86 |
constexpr uint32_t operator()() |
| 87 |
{ |
| 88 |
|
| 89 |
auto oldState = state; |
| 90 |
state = oldState * 6364136223846793005ULL + (SEED | 1); |
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
auto xorShifted = uint32_t(((oldState >> 18) ^ oldState) >> 27); |
| 95 |
auto rot = int(oldState >> 59); |
| 96 |
return (xorShifted >> rot) | (xorShifted << ((-rot) & 31)); |
| 97 |
} |
| 98 |
|
| 99 |
private: |
| 100 |
uint64_t state = SEED; |
| 101 |
}; |
| 102 |
|
| 103 |
|
| 104 |
[[nodiscard]] constexpr float getCanonicalFloat(uint32_t u) |
| 105 |
{ |
| 106 |
uint32_t b = 1 << 23; |
| 107 |
uint32_t m = b - 1; |
| 108 |
return float(u & m) / float(b); |
| 109 |
} |
| 110 |
|
| 111 |
#endif |