C Interview Questions and Answers

 

How can I get random integers in a certain range?

The obvious way,



rand() % N /* POOR */



(which tries to return numbers from 0 to N-1) is poor, because the low-order bits
of many random number generators are distressingly non-random.



A better method is something like



(int)((double)rand() / ((double)RAND_MAX + 1) * N)



If you'd rather not use floating point, another method is



rand() / (RAND_MAX / N + 1)



If you just need to do something with probability 1/N, you could use



if(rand() < (RAND_MAX+1u) / N)



All these methods obviously require knowing RAND_MAX (which ANSI #defines in <stdlib.h>),
and assume that N is much less than RAND_MAX.



When N is close to RAND_MAX, and if the range of the random number generator is
not a multiple of N (i.e. if (RAND_MAX+1) % N != 0), all of these methods break
down: some outputs occur more often than others. (Using floating point does not
help; the problem is that rand returns RAND_MAX+1 distinct values, which cannot
always be evenly divvied up into N buckets.) If this is a problem, about the only
thing you can do is to call rand multiple times, discarding certain values:



unsigned int x = (RAND_MAX + 1u) / N;



unsigned int y = x * N;



unsigned int r;



do {



r = rand();



} while(r >= y);



return r / x;

Posted by:Richards