Amazon Interview Question: Rand(7) from Rand(5)... | Glassdoor

## Interview Question

Senior Software Engineer Interview Beijing, Beijing (China)

# Rand(7) from Rand(5)

0

The simple solution is to implement RandBin() using Rand5().

int RandBin()
{

}

David on Oct 25, 2011
3

Sorry this UI posts without warning

int RandBin()
{
int rand5Res = Rand5();

return rand5Res < 2 ? 0 : rand5Res < 4 ? 1 : RandBin();
}

And then use RandBin() to implement Rand7;

int Rand7()
{
int rand = RandBin() << 2 | RandBin() << 1 | RandBin();

return rand < 7 ? rand : Rand7();
}

Anonymous on Oct 25, 2011
3

int rand7()
{
while(1)
{
int n = ((rand5()%2)*4 + (rand5()%2)*2 + (rand5()%2)*1);
if(n == 0)
continue;
return n;
}
}

The rand5()%2 will generate 0 and 1 with equal probability and we need 3 bits since we are going from 000 upto 111. So we call this function thrice for each bit position.

simple_coder on Dec 2, 2011
1

Above answer is not correct because 0 is not returned. We need equal probability for all 0, 1,2,3,4,5,6. The modified would be:

int rand7()
{
while(1)
{
int n = ((rand5()%2)*4 + (rand5()%2)*2 + (rand5()%2)*1;
if(n==0)
continue;
return n-1;
}
}

Anonymous on Feb 7, 2012
0

Java:
Random r = new Random();
r.nextInt(5)+r.nextInt(5)%3

Anonymous on Aug 6, 2012
1

( rand5() + rand5() + rand 5() + rand5() + rand5 () + rand5() + rand5() ) % 7

-suhane

ravi on Nov 20, 2012
0

int r = rand5() *5 + rand5()
while (r>=21){
r = rand5() *5 + rand5();
}
return r%7;

Anonymous on Jul 7, 2016