fork download
  1. // A few common random functions. (1.03)
  2.  
  3. #include <algorithm>
  4. #include <experimental/iterator>
  5. #include <random>
  6. #include <iostream>
  7. using namespace std;
  8.  
  9. // Initialize generator with non-deterministic seed.
  10.  
  11. static thread_local default_random_engine re_(random_device{}());
  12.  
  13. // Real in the range [0, 1).
  14.  
  15. double randreal()
  16. {
  17. uniform_real_distribution<double> pick(0, 1);
  18. return pick(re_);
  19. }
  20.  
  21. // Integer in the range [lo, hi].
  22.  
  23. int randint(int lo, int hi)
  24. {
  25. uniform_int_distribution<> pick(lo, hi);
  26. return pick(re_);
  27. }
  28.  
  29. // Boolean where probability of true is p and false is (1-p).
  30.  
  31. bool randbool(double p)
  32. {
  33. bernoulli_distribution pick(p);
  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 0s 5268KB
stdin
Standard input is empty
stdout
[0.563179, 0.454795, 0.124613, 0.726201, 0.191695, 0.667348, 0.528444, 0.851115, 0.456227, 0.997265]
[-5, -4, 1, -1, 0, -3, 5, 5, -2, 0]
[1, 1, 1, 0, 0, 0, 0, 1, 1, 0]