I tried a lot but could not get a solution for this problem
Function returns numbers in range
[1,6]
with equal probability. You can use library'srand()
function and you can assume implementation ofrand()
returns number in range number in range[0,RAND_MAX]
with equal probability.
We'll do this in multiple steps.
You need to generate a number in the range
[1, 6]
, inclusive.You have a random number generator that will generate numbers in the range
[0..RAND_MAX]
.Let's say you wanted to generate numbers in the range
[0..5]
. You can do this:You can use that technique to So given a range of
[0, high]
, you can generate a random number, divide byRAND_MAX
, multiply byhigh
, and round the result.Your range is
[1, 6]
, so you have to add another step. You want to generate a random number in the range[0, 5]
, and then add 1. Or, in general, to generate a random number in a given range,[low, high]
, you write:Obviously you can combine some of those operations. I just showed them individually to illustrate.
Basically you are looking for using the
operator%
(modolus).If you are afraid that
RAND_MAX % 6 != 0
and the solution will be biased - you just need to 'throw' some numbers (up to 5) out and redraw if you get them:PS, if you want to draw a 'real' number, it can be done with:
Note that it is not a 'real' number, and the density between two numbers is
1/RAND_MAX-1