1 #ifndef MEDUSA_BITS_UTILS_RANDUTILS_HPP_
2 #define MEDUSA_BITS_UTILS_RANDUTILS_HPP_
27 std::random_device rd;
29 }
catch (std::exception& e) {
30 return std::chrono::system_clock::now().time_since_epoch().count();
34 template <
typename T,
typename URNG>
35 T
random_choice(
const Range<T>& elements,
const Range<double>& weights,
bool normed,
52 bool normed =
false) {
58 template <
typename T,
typename URNG>
62 if (actual_weights.empty()) {
64 actual_weights.assign(elements.
size(), 1.0 / elements.
size());
67 "Weights not specified for all elements. Got %d weights but %d elements.",
70 double sum = std::accumulate(actual_weights.begin(), actual_weights.end(), 0.0);
71 for (
auto& w : actual_weights) w /= sum;
73 std::uniform_real_distribution<double> uniform(0, 1);
74 double x = uniform(generator);
75 for (
int i = 0; i < elements.
size(); ++i) {
76 if (x < actual_weights[i])
return elements[i];
77 x -= actual_weights[i];
79 assert_msg(
false,
"Should never get here, you might have claimed the weights "
80 "are normalized, but weren't.");
86 #endif // MEDUSA_BITS_UTILS_RANDUTILS_HPP_