// A few common random functions. (1.04)
#include <stdexcept>
#include <random>
#include <algorithm>
#include <experimental/iterator>
#include <iostream>
using namespace std;
// Initialize generator with non-deterministic seed.
static thread_local default_random_engine re_(random_device{}());
// Real uniformly distributed on the interval [0, 1).
double randreal()
{
uniform_real_distribution<double> pick(0, 1);
return pick(re_);
}
// Integer uniformly distributed on the closed interval [lo, hi].
int randint(int lo, int hi)
{
if (!(lo <= hi))
throw invalid_argument("lo must be less than or equal to hi");
uniform_int_distribution<> pick(lo, hi);
return pick(re_);
}
// Boolean where the probability of true is p and false is (1-p).
bool randbool(double p)
{
if (!(0.0 <= p && p <= 1.0))
throw invalid_argument("p must be between 0 and 1 (inclusive)");
bernoulli_distribution pick(p);
return pick(re_);
}
// Main.
template<typename Func, typename... Args>
void display(int n, Func f, Args... args)
{
cout << '[';
generate_n(experimental::make_ostream_joiner(cout, ", "), n,
[=]{ return f(args...); });
cout << "]\n";
}
int main()
{
display(10, randreal);
display(10, randint, -5, 5);
display(10, randbool, 0.5);
}
Ly8gQSBmZXcgY29tbW9uIHJhbmRvbSBmdW5jdGlvbnMuICgxLjA0KQoKI2luY2x1ZGUgPHN0ZGV4Y2VwdD4KI2luY2x1ZGUgPHJhbmRvbT4KI2luY2x1ZGUgPGFsZ29yaXRobT4KI2luY2x1ZGUgPGV4cGVyaW1lbnRhbC9pdGVyYXRvcj4KI2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKLy8gSW5pdGlhbGl6ZSBnZW5lcmF0b3Igd2l0aCBub24tZGV0ZXJtaW5pc3RpYyBzZWVkLgoKc3RhdGljIHRocmVhZF9sb2NhbCBkZWZhdWx0X3JhbmRvbV9lbmdpbmUgcmVfKHJhbmRvbV9kZXZpY2V7fSgpKTsKCi8vIFJlYWwgdW5pZm9ybWx5IGRpc3RyaWJ1dGVkIG9uIHRoZSBpbnRlcnZhbCBbMCwgMSkuCgpkb3VibGUgcmFuZHJlYWwoKQp7CiAgICB1bm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Cn0KCmludCBtYWluKCkKewogICAgZGlzcGxheSgxMCwgcmFuZHJlYWwpOwogICAgZGlzcGxheSgxMCwgcmFuZGludCwgLTUsIDUpOwogICAgZGlzcGxheSgxMCwgcmFuZGJvb2wsIDAuNSk7Cn0=
[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]