Skip to content

Commit f0e337e

Browse files
committed
feat: Add Linear Congruential Generator (LCG) implementation for compile-time pseudo-random number generation
1 parent a2d08ca commit f0e337e

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

weilycoder/const_rand.hpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)