One common way of choosing a random number in [0, n) is to take the result of rand() modulo n: rand() % n. However, even if the r
One approach you can do is the following:
Knowing the value of N, you make R_MAX = ((RAND_MAX + 1) / N) * N; for uniformity.
So you can do your custom rand() function:
int custom_rand(int mod) {
int x = rand();
const int R_MAX = ((RAND_MAX + 1) / mod) * mod;
while (x > R_MAX) { // discard the result if it is bigger
x = rand();
}
return (x % mod);
}