I would like to generate a random number between 0 and 3 and I have the following in my code:
int random = rand() % 4;
This works fine but I would like it to generate 1, 2, and 3 most of the time and 0 only occasionally.
What is the best way to go about this? What are the names of common algorithms to address this problem?
how many numbers have you tested this on? if it is actually true you can instead generate a range from say 0->3999 using
a = rand()%4000
and useint = a/1000
this should remove the weight of the apparently under produced zero.Just code exactly what you want:
You can change the percentage of time zero is returned to whatever you want.
You need to find a probability distribution that works for your case. Since you're only talking about the numbers 0-3 this is quite easy, you could either call
rand()
again if the first result is a 0, or you could use weights:This isn't a particularly elegant, but hopefully it shows you how you can create a custom distribution to fit your needs.
You didn't give exact proportions, but suppose you want 1, 2, and 3 to each occur 32% of the time, and 0 to occur the other 4%. Then you could write:
(Obviously you'd need to adjust that for different proportions. And the above is just one approach; many similar approaches could work.)
Here's one way. Suppose you want 0, 1, 2, 3 to have a distribution of 5%, 20%, 30%, 45%.
You could do it like this:
Of course it doesn't have to be done with floating-point. I just did it this way since it's more intuitive.
You can use the discrete_distribution class from the random library.
Demo: http://ideone.com/z8bq4
If you can't use C++11, these classes also exist in boost.