53 lines
1.4 KiB
C++
53 lines
1.4 KiB
C++
#ifndef RANDOM_H_
|
|
#define RANDOM_H_
|
|
|
|
#include <random>
|
|
#include <vector>
|
|
|
|
namespace sc {
|
|
|
|
class random {
|
|
public:
|
|
static random& instance() { return singleton; }
|
|
|
|
// forbid copying
|
|
random(const random&) = delete;
|
|
random& operator=(const random&) = delete;
|
|
|
|
// forbid moving
|
|
random(random&&) = delete;
|
|
random& operator=(random&&) = delete;
|
|
|
|
std::default_random_engine& engine() { return _reng; }
|
|
|
|
static bool boolean();
|
|
static int int_between(int from, int to);
|
|
static double double01();
|
|
static double double_between(double from, double to);
|
|
|
|
template <typename T>
|
|
static T choice(const std::vector<T>& vec) {
|
|
std::uniform_int_distribution<int> dist {0, static_cast<int>(vec.size()) - 1};
|
|
return vec[dist(instance()._reng)];
|
|
}
|
|
|
|
template <typename T, typename Iter>
|
|
static T choice(Iter from, Iter to) {
|
|
std::uniform_int_distribution<int> dist {0, static_cast<int>(to - from) - 1};
|
|
return *(from + dist(instance()._reng));
|
|
}
|
|
|
|
private:
|
|
static random singleton;
|
|
|
|
random() = default;
|
|
~random() = default;
|
|
|
|
std::random_device _rdev {};
|
|
std::default_random_engine _reng {_rdev()};
|
|
};
|
|
|
|
}
|
|
|
|
#endif // RANDOM_H_
|