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.
Best Puzzles asked in Job Interviews and their solutions. Huge and wise online repository of riddles and questions asked in technical, management, software, aptitude, stress and programming rounds. JobPuzzles.com is often called a paradise for people preparing for MNCs like Google, Microsoft, Facebook, Adobe, Symantec, Expedia, TCS, Dell, Amazon etc. Our Plan for you -> Dream MNCs. Be Prepared @JobPuzzles . Get Selected. Do like the FB Page/Group for the Learners Consortium. www.w3lc.com
This comment has been removed by the author.
ReplyDeleteint genRand1to7 ()
ReplyDelete{
int i = genRand1to5();
int j = genRand1to5();
return (i+j)%8 ;
}
It's not uniform.
DeleteWhat about :
ReplyDeleteLet 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.
Great discussion by Aditi and Aduait.
ReplyDeleteThough 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