Re: some interview questions



Jim Gibson <james.t.gibson@xxxxxxxxxxxxx> wrote:
Digital Puer wrote:
1. Given a function which produces a random integer in the range
1 to 5, write a function which produces a random integer in the
range 1 to 7.

For a solution to 1., how about this ...

int random17( )
{
int sum = 0;
int result;

// call function 7 times, summing the result [1..5]
for( int i = 0; i < 7; ++i)
sum += random15( );

// integer division truncates quotient
result = sum / 5;

// round up
if( (sum % 7) > 3 )
++result;

return result;
}

That produces nothing like the required distribution. There are 5^7
equiprobable possible outcomes from the 7 calls of random15(). Since
this isn't a multiple of 7, the probabilities of getting each of 1 .. 7
can't be equal.

More generally, the problem can't be solved using a fixed number of calls
to random15().


Mike Guy
.