|
| 1 | +#ifndef WEILYCODER_CONST_RAND_HPP |
| 2 | +#define WEILYCODER_CONST_RAND_HPP |
| 3 | + |
| 4 | +#include <cstdint> |
| 5 | + |
| 6 | +namespace weilycoder { |
| 7 | +/** |
| 8 | + * @brief Linear Congruential Generator (LCG) to produce pseudo-random numbers |
| 9 | + * at compile-time. |
| 10 | + * @tparam a The multiplier. |
| 11 | + * @tparam c The increment. |
| 12 | + * @tparam m The modulus. |
| 13 | + * @param state The current state of the generator. |
| 14 | + * @return The next state of the generator. |
| 15 | + */ |
| 16 | +template <uint32_t a, uint32_t c, uint64_t m> |
| 17 | +constexpr uint32_t &lcg_next(uint32_t &state) { |
| 18 | + state = (static_cast<uint64_t>(a) * state + c) % m; |
| 19 | + return state; |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * @brief LCG using parameters from "Minimal Standard" by Park and Miller. |
| 24 | + * @param state The current state of the generator. |
| 25 | + * @return The next state of the generator. |
| 26 | + */ |
| 27 | +constexpr uint32_t &lcg_minstd(uint32_t &state) { |
| 28 | + return lcg_next<48271, 0, 2147483647>(state); |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * @brief LCG using parameters from "minstd_rand0" by Park and Miller. |
| 33 | + * @param state The current state of the generator. |
| 34 | + * @return The next state of the generator. |
| 35 | + */ |
| 36 | +constexpr uint32_t &lcg_minstd_rand0(uint32_t &state) { |
| 37 | + return lcg_next<16807, 0, 2147483647>(state); |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * @brief LCG using parameters from "Numerical Recipes". |
| 42 | + * @param state The current state of the generator. |
| 43 | + * @return The next state of the generator. |
| 44 | + */ |
| 45 | +constexpr uint32_t &lcg_nr(uint32_t &state) { |
| 46 | + return lcg_next<1103515245, 12345, 4294967296>(state); |
| 47 | +} |
| 48 | +} // namespace weilycoder |
| 49 | + |
| 50 | +#endif |
0 commit comments