Advertisement
Tainel

src/base/features/random.hpp

May 26th, 2023 (edited)
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | Source Code | 0 0
  1. #pragma once
  2.  
  3. #include"base/dependencies/index.hpp"
  4.  
  5. #include"debug.hpp"
  6. #include"floats.hpp"
  7. #include"integers.hpp"
  8. #include"metaprogramming.hpp"
  9.  
  10. // Return a random unsigned 64-bit seed.
  11. u64 random_seed(){
  12.     // Read a hardware-generated random unsigned 64-bit value.
  13.     u64 seed=0;
  14.     _rdrand64_step(&seed);
  15.     // Add noise using a standard uniform random number generator.
  16.     static random_device rd;
  17.     seed^=(U64(rd())<<32)|rd();
  18.     // Add noise using the current time.
  19.     seed^=chrono::steady_clock::now().time_since_epoch().count();
  20.     // Add noise using a random address from the heap.
  21.     seed^=reinterpret_cast<u64>(make_unique<char>().get());
  22.     // Return the final value.
  23.     return seed;
  24. }
  25.  
  26. // Default random engine.
  27. using random_engine=CXX::sfmt19937_64;
  28.  
  29. // Generic random utility type.
  30. template<class RandomEngine=random_engine>class random_machine{
  31.     // Seed unsigned integer type.
  32.     using seed_type=RandomEngine::result_type;
  33.     // Initialized random number engine.
  34.     static inline RandomEngine engine{static_cast<seed_type>(random_seed())};
  35. public:
  36.     // Generate a random integer in `[l,r)`.
  37.     template<Integer Int>static Int integer(Int const l,Int const r){
  38.         ASSERT(l<r);
  39.         return uniform_int_distribution{l,r-1}(engine);
  40.     }
  41.     // Generate a random integer in `[0,n)`.
  42.     template<Integer Int>static Int integer(Int const n){
  43.         ASSERT(n>0);
  44.         return integer<Int>(0,n);
  45.     }
  46.     // Generate a random real in `[0,1)`.
  47.     template<Float Real=f64>
  48.     static Real real(){return uniform_real_distribution<Real>{}(engine);}
  49.     // Mix up the given container range randomly.
  50.     template<class RandomIt>
  51.     static void mixup(RandomIt first,RandomIt last){shuffle(first,last,engine);}
  52. };
  53.  
  54. // Default random utility type.
  55. template class random_machine<>;
  56. using rnd=random_machine<>;
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement