fork(1) download
  1. // Most common random functions. (2.00)
  2.  
  3. #include <random>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. class Random {
  8. static thread_local default_random_engine s_re;
  9.  
  10. public:
  11. // Real in the range [0, 1) (exclusive).
  12. static double randreal() {
  13. uniform_real_distribution<double> pick(0.0, 1.0);
  14. return pick(s_re);
  15. }
  16.  
  17. // Integer in the range [lo, hi] (inclusive).
  18. static int randint(int lo, int hi) {
  19. uniform_int_distribution<> pick(lo, hi);
  20. return pick(s_re);
  21. }
  22.  
  23. // Boolean with probability {p true | (1-p) false}.
  24. static bool randbool(double p) {
  25. bernoulli_distribution pick(p);
  26. return pick(s_re);
  27. }
  28. };
  29.  
  30. thread_local default_random_engine Random::s_re(random_device{}());
  31.  
  32. // Show.
  33.  
  34. int main() {
  35. int n = 10;
  36. for (int i = 0; i < n; i++)
  37. cout << Random::randreal() << ' ';
  38. cout << endl;
  39. for (int i = 0; i < n; i++)
  40. cout << Random::randint(-n/2, n/2) << ' ';
  41. cout << endl;
  42. for (int i = 0; i < n; i++)
  43. cout << Random::randbool(0.5) << ' ';
  44. cout << endl;
  45. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
0.87802 0.71944 0.793862 0.89195 0.584331 0.454796 0.593583 0.239353 0.250641 0.593872 
-3 -5 -2 3 -5 4 2 -2 -2 3 
1 1 1 1 1 0 0 0 0 0