7 #ifndef NSAS_RANDOM_NUMBER_GENERATOR_H
8 #define NSAS_RANDOM_NUMBER_GENERATOR_H
18 #include <boost/random/mersenne_twister.hpp>
19 #include <boost/random/uniform_int.hpp>
20 #include <boost/random/uniform_real.hpp>
21 #include <boost/random/variate_generator.hpp>
59 min_(
std::min(min, max)), max_(
std::max(min, max)),
60 dist_(min_, max_), generator_(rng_, dist_)
67 "when initializing UniformRandomIntegerGenerator");
71 rng_.seed(time(NULL));
83 boost::uniform_int<> dist_;
85 boost::variate_generator<boost::mt19937&, boost::uniform_int<> > generator_;
104 dist_(0, 1.0), uniform_real_gen_(rng_, dist_), min_(min)
108 areProbabilitiesValid(probabilities);
111 std::partial_sum(probabilities.begin(), probabilities.end(),
112 std::back_inserter(cumulative_));
114 rng_.seed(time(NULL));
120 dist_(0, 1.0), uniform_real_gen_(rng_, dist_), min_(0)
129 void reset(
const std::vector<double>& probabilities,
size_t min = 0)
132 areProbabilitiesValid(probabilities);
138 std::partial_sum(probabilities.begin(), probabilities.end(),
139 std::back_inserter(cumulative_));
148 return std::lower_bound(cumulative_.begin(), cumulative_.end(), uniform_real_gen_())
149 - cumulative_.begin() + min_;
165 void areProbabilitiesValid(
const std::vector<double>& probabilities)
const
167 double sum = probabilities.empty() ? 1.0 : 0.0;
168 for (
const double it : probabilities) {
170 if (it < 0.0 || it > 1.0) {
172 "probability must be in the range 0..1");
178 double epsilon = 0.0001;
180 if (std::fabs(sum - 1.0) >= epsilon) {
181 isc_throw(SumNotOne,
"Sum of probabilities is not equal to 1");
187 std::vector<double> cumulative_;
189 boost::uniform_real<> dist_;
194 typedef boost::variate_generator<boost::mt19937&, boost::uniform_real<> > UniformRealGenerator;
195 UniformRealGenerator uniform_real_gen_;
204 #endif//NSAS_RANDOM_NUMBER_GENERATOR_H
WeightedRandomIntegerGenerator(const std::vector< double > &probabilities, size_t min=0)
Constructor.
WeightedRandomIntegerGenerator()
Default constructor.
SumNotOne(const char *file, size_t line, const char *what)
InvalidProbValue(const char *file, size_t line, const char *what)
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
size_t operator()()
Generate weighted random integer.
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
Defines the logger used by the top-level component of kea-dhcp-ddns.
void reset(const std::vector< double > &probabilities, size_t min=0)
Reset the probabilities.
InvalidLimits(const char *file, size_t line, const char *what)
std::vector< uint8_t > random(size_t len)
Generate random value.
Weighted random integer generator.