Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <chrono>
- #include <iostream>
- #include <map>
- namespace Random {
- class LCG {
- static constexpr uint64_t const A = 0x5851F42D4C957F2D;
- static constexpr uint64_t const C = 0x14057B7EF767814F;
- static constexpr uint64_t const M = 0xFFFFFFFFFFFFFFFF;
- uint64_t this_seed;
- auto now() noexcept {
- using namespace std::chrono;
- auto const output = high_resolution_clock::now();
- return output.time_since_epoch().count();
- }
- public:
- LCG() noexcept
- : this_seed(now()) {
- }
- LCG(uint64_t const value) noexcept
- : this_seed(value) {
- }
- void seed() noexcept {
- this_seed = now();
- }
- void seed(uint64_t const value) noexcept {
- this_seed = value;
- }
- // [0, 2 ^ 64 - 1)
- auto next() noexcept {
- this_seed = (this_seed * A + C) & M;
- return this_seed;
- }
- void discard(uint64_t const amount) noexcept {
- for (uint64_t i = 0; i != amount; ++i) {
- next();
- }
- }
- // [0, 1)
- double get() noexcept {
- return static_cast<double>(next()) / M;
- }
- // x == (-1 | 0 | 1) ? 0 : x > 0 ? [0, x) : (x, 0]
- int64_t get(int64_t const x) noexcept {
- return static_cast<int64_t>(get() * x);
- }
- // [a, b)
- int64_t get(int64_t const a, int64_t const b) noexcept {
- return a + static_cast<int64_t>(get() * (b - a));
- }
- };
- }
- int main() {
- Random::LCG lcg(0);
- std::map<int64_t, uint64_t> buckets;
- for (int i = 0; i != 1000000; ++i) {
- ++buckets[lcg.get(50)];
- }
- for (auto const [a, b] : buckets) {
- std::cout << a << 't' << b << 'n';
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment