How to generate a random number with equal probability in a given interval

algorithm, random

Solution

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:

int r = rand();  // gives you a number from 0 to RAND_MAX
double d = r / RAND_MAX;  // gives you a number from 0 to 1
double val = d * 5; // gives you a number from 0 to 5
int result = round(d);  // rounds to an integer

You can use that technique to So given a range of `[0, high]`, you can generate a random number, divide by `RAND_MAX`, multiply by `high`, 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:

int r = rand();
double d = r / RAND_MAX;
int range = high - low + 1;
double val = d * range;
result = round(val);

Obviously you can combine some of those operations. I just showed them individually to illustrate.

Problem

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's `rand()` function and you can assume implementation of `rand()` returns number in range number in range `[0,RAND_MAX]` with equal probability.

Original source

Related problems