## Friday, August 30, 2013

### Generate random 7 from random 5

Write a function to generate a random number between 1 and 7. You have been given a function that generates a random number between 1 and 5. The distribution between each of the numbers must be uniform.

#### 5 comments:

1. This comment has been removed by the author.

2. int genRand1to7 ()
{
int i = genRand1to5();
int j = genRand1to5();
return (i+j)%8 ;
}

1. It's not uniform.

3. What about :

Let f() is retRand1to5() and g() is getRand1to7() then as per @AditiPal

g() = (f()+f())%8;

what about:
n = f();
g() = n+(log of n base sqrt(5));

Wouldn't it provide a more uniform distribution.

4. Great discussion by Aditi and Aduait.

Though both solutions are too close, but there is another method that can give 100% random depending on retRand1to5() function. Hint:

We know foo() returns integers from 1 to 5. How we can ensure that integers from 1 to 7 occur with equal probability?
If we somehow generate integers from 1 to a-multiple-of-7 (like 7, 14, 21, …) with equal probability, we can use modulo division by 7 followed by adding 1 to get the numbers from 1 to 7 with equal probability.

We can generate from 1 to 21 with equal probability using the following expression.

5*foo() + foo() -5