kevkul

random.h

Jun 4th, 2020
1,036
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <cstdint>
  4. #include <limits>
  5. #include <random>
  6. #include <type_traits>
  7.  
  8. namespace ift630 {
  9.  
  10. template <typename RNG, typename T>
  11. auto random(RNG &&rng, const T lower_bound, const T upper_bound) noexcept -> T {
  12.   static_assert(std::is_arithmetic<T>::value);
  13.   static_assert(!std::is_same<T, bool>::value);
  14.  
  15.   auto dist = [lower_bound, upper_bound]() {
  16.     if constexpr (std::is_floating_point<T>::value) {
  17.       return std::uniform_real_distribution<T>{lower_bound, upper_bound};
  18.     } else {
  19.       return std::uniform_int_distribution<T>{lower_bound, upper_bound};
  20.     }
  21.   }();
  22.  
  23.   auto engine = std::default_random_engine{rng};
  24.   return dist(engine);
  25. }
  26.  
  27. template <typename T>
  28. auto random(T lower_bound, T upper_bound) noexcept -> T {
  29.   static std::random_device r{};
  30.   return random(r(), lower_bound, upper_bound);
  31. }
  32.  
  33. template <typename T>
  34. auto random() noexcept -> T {
  35.   if constexpr (std::is_floating_point<T>::value) {
  36.     return random<T>(0.0, 1.0);
  37.   } else if constexpr (std::is_same<T, bool>::value) {
  38.     // uint16_t because the C++ standard says std::uniform_int_distribution on
  39.     // 8-bit integer types is undefined behavior for some dumb reason
  40.     return static_cast<bool>(random<uint16_t>(0, 1));
  41.   } else {
  42.     return random<T>(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
  43.   }
  44. }
  45.  
  46. }  // namespace ift630
Advertisement
Add Comment
Please, Sign In to add comment