I need to generate random numbers from a very small range (sometimes just 0-1 ie a coin toss). The accuracy of distribution isn't particularly important but I do need to avoid long sequences of the same number.
I have tried generating random numbers using the C++11 std::uniform_int_distribution and while the distribution is very good, it can generate sequences of 15+ of a single value in a row (note that I don't really re-seed the RNG every time).
int randomInRange(int range)
{
std::mt19937 rng(0);
auto seed = std::random_device{}();
rng.seed(seed);
std::uniform_int_distribution<int> dist(0, range - 1);
return dist(rng);
}
I built a test program (https://ideone.com/f9p0WJ) which showed that it could generate up to 18 heads in a row. I would like to reduce the probability beyond what the uniform distribution gives, for example halve the probability of a run of 3 and no chance of a run of 5.
Is there a generalised solution to this? My naive solution is to keep some history and discard when I detect too long a sequence (with some probability < 1) but perhaps someone smarter than me has already thought about this?
Aucun commentaire:
Enregistrer un commentaire