fork download
  1. // A few common random functions. (1.05)
  2.  
  3. #include <random>
  4. #include <limits>
  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. return generate_canonical<double, numeric_limits<double>::digits>(re_);
  19. }
  20.  
  21. // Integer uniformly distributed on the closed interval [a, b].
  22.  
  23. int randint(int a, int b)
  24. {
  25. uniform_int_distribution<> pick(min(a, b), max(a, b));
  26. return pick(re_);
  27. }
  28.  
  29. // Boolean where the probability of true is p and false is (1-p).
  30.  
  31. bool randbool(double p)
  32. {
  33. bernoulli_distribution pick(min(max(p, 0.0), 1.0));
  34. return pick(re_);
  35. }
  36.  
  37. // Main.
  38.  
  39. template<typename Func, typename... Args>
  40. void display(int n, Func f, Args... args)
  41. {
  42. cout << '[';
  43. generate_n(experimental::make_ostream_joiner(cout, ", "), n,
  44. [=]{ return f(args...); });
  45. cout << "]\n";
  46. }
  47.  
  48. int main()
  49. {
  50. display(10, randreal);
  51. display(10, randint, -5, 5);
  52. display(10, randbool, 0.5);
  53. }
Success #stdin #stdout 0.01s 5256KB
stdin
Standard input is empty
stdout
[0.766086, 0.947016, 0.940326, 0.256573, 0.446622, 0.387364, 0.568334, 0.874144, 0.423408, 0.4222]
[5, 0, 4, 5, -3, -5, -3, 2, 4, -5]
[1, 0, 1, 1, 0, 0, 1, 0, 0, 1]