mercredi 25 août 2021

Generate random numbers with equal probabilities in c++

For example, array of pairs of ranges p={[23, 28], [11, 14], [31, 39]}

You have to return random number such that this number should be:

  1. In any one of these pairs
  2. Each number in these ranges should have equal probability of being chosen.

I can easily generate a random number that lies between any of these intervals like

int x=(rand()%(p[i].second-p[i].first) )+ p[i].first;

How can I generate a random number that can lie in any interval in the array and that too with equal probability.




Aucun commentaire:

Enregistrer un commentaire