SHARE
TWEET

Random.h (C++11)

ulfben Sep 23rd, 2016 (edited) 109 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //based on Cheinan Marks talk at CPPCon2016: https://www.youtube.com/watch?v=4_QO1nm7uJs
  2. #pragma once
  3. #include <random>
  4. class Random {
  5.     static std::mt19937& rng() {
  6.         static std::mt19937 u{};
  7.         return u;
  8.     }
  9. public:    
  10.     static void randomize() {
  11.         static std::random_device rd{};
  12.         rng().seed(rd());
  13.     }  
  14.     static unsigned char color() {//0-255 inclusive
  15.         static std::uniform_int_distribution<> dist{0, 255};       
  16.         return static_cast<unsigned char>(dist(rng()));
  17.     }  
  18.     static int getInt(int from, int thru) {//[from,trhu] (inclusive)
  19.         static std::uniform_int_distribution<int> dist{};
  20.         using parm_t = decltype(dist)::param_type;
  21.         return dist(rng(), parm_t{ from, thru });
  22.     }
  23.     static float getFloat(float from = 0.0f, float upto = 1.0f) {// [from, upto) (exclusive)
  24.         static std::uniform_real_distribution<float> dist{};
  25.         using parm_t = decltype(dist)::param_type;
  26.         return dist(rng(), parm_t{ from, upto });
  27.     }
  28.     static double getDouble(double from = 0.0, double upto = 1.0) {// [from, upto) (exclusive)
  29.         static std::uniform_real_distribution<double> dist{};
  30.         using parm_t = decltype(dist)::param_type;
  31.         return dist(rng(), parm_t{ from, upto });
  32.     }
  33.     template<class T>
  34.     static T getNumber(T min, T max) {
  35.         static std::uniform_int_distribution<T> dist{};
  36.         using parm_t = decltype(dist)::param_type;
  37.         return dist(rng(), parm_t{ min, max });
  38.     };
  39.     static float getNumber(float from, float upto) {// [from, upto) (exclusive)
  40.         return getFloat(from, upto);
  41.     }
  42.     static double getNumber(double from, double upto) {// [from, upto) (exclusive)
  43.         return getDouble(from, upto);
  44.     }
  45. };
RAW Paste Data
Top