What
Returning rand() % N
does not uniformly give a number in the range [0, N)
, unless N
divides the length of the interval into which rand()
returns (i.e. is a power of 2).
How to do it correctly
Why
To change the range of rand()
is to divide it into boxes; for example, if RAND_MAX == 11
and you want a range of 1..6
, you should assign {0,1}
to 1, {2,3}
to 2, and so on. These are disjoint, equally-sized intervals and thus are uniformly and independently distributed.