fork download
  1. // A few common random functions. (1.04)
  2.  
  3. #include <stdexcept>
  4. #include <random>
  5. #include <algorithm>
  6. #include <experimental/iterator>
  7. #include <iostream>
  8. using namespace std;
  9.  
  10. // Initialize generator with non-deterministic seed.
  11.  
  12. static thread_local default_random_engine re_(random_device{}());
  13.  
  14. // Real uniformly distributed on the interval [0, 1).
  15.  
  16. double randreal()
  17. {
  18. uniform_real_distribution<double> pick(0, 1);
  19. return pick(re_);
  20. }
  21.  
  22. // Integer uniformly distributed on the closed interval [lo, hi].
  23.  
  24. int randint(int lo, int hi)
  25. {
  26. if (!(lo <= hi))
  27. throw invalid_argument("lo must be less than or equal to hi");
  28. uniform_int_distribution<> pick(lo, hi);
  29. return pick(re_);
  30. }
  31.  
  32. // Boolean where the probability of true is p and false is (1-p).
  33.  
  34. bool randbool(double p)
  35. {
  36. if (!(0.0 <= p && p <= 1.0))
  37. throw invalid_argument("p must be between 0 and 1 (inclusive)");
  38. bernoulli_distribution pick(p);
  39. return pick(re_);
  40. }
  41.  
  42. // Main.
  43.  
  44. template<typename Func, typename... Args>
  45. void display(int n, Func f, Args... args)
  46. {
  47. cout << '[';
  48. generate_n(experimental::make_ostream_joiner(cout, ", "), n,
  49. [=]{ return f(args...); });
  50. cout << "]\n";
  51. }
  52.  
  53. int main()
  54. {
  55. display(10, randreal);
  56. display(10, randint, -5, 5);
  57. display(10, randbool, 0.5);
  58. }
Success #stdin #stdout 0.01s 5248KB
stdin
Standard input is empty
stdout
[0.293073, 0.779095, 0.340452, 0.210086, 0.692613, 0.359162, 0.768095, 0.851765, 0.659738, 0.932233]
[-5, 0, -2, -2, 2, -1, -2, 5, -5, 4]
[0, 1, 0, 0, 1, 1, 0, 0, 1, 1]