[Solved] Weighted random: roll dice 1 to 1000, averages to 100… which std::distribution to use?


You might be able to use a binomial distribution if its properties satisfy your needs. It gives you control over the maximum value and the mean. You can even choose a non-integer mean if you want to. You cannot choose the minimum, as that is always zero, so you may have to offset the result:

int weighted_rand(int min, int max, double avg) {
  std::binomial_distribution distribution{
    max - min,                // number of trials
    (avg - min) / (max - min) // success probability of each trial
  };
  return distribution(prng) + min;
}

Since a normal distribution is often used for continuous variables in the absence of more detailed information, using the binomial distribution as its discrete counterpart might be be a good solution.

But this is far from the only one, and depending on your use case, it might be terrible. You need to provide more details. As I wrote in a comment, a “random” function which always returns 100 would satisfy the constraints for range and average. As would a function which returns 1 in 80% of the cases, 370 in 16% of the cases and 1000 in 4% of the cases. So I assume you have some additional expectations for your distribution, but you need to make them explicit to get a suitable answer. The above assumes a kind of bell-shaped distribution.

0

solved Weighted random: roll dice 1 to 1000, averages to 100… which std::distribution to use?