Amazon.com

www.amazon.com
Work in HR? Unlock Free Profile

# Amazon.comSenior Software Engineer Interview Question

I interviewed in Beijing, Beijing (China) and was asked:
"Rand(7) from Rand(5)"

Part of a Senior Software Engineer Interview Review - one of 4,652 Amazon.com Interview Reviews

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

int RandBin()
{

}
- David on Oct 25, 2011
3
of 4
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
2
of 2
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
of 1
vote
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
of 1
vote
Java:
Random r = new Random();
r.nextInt(5)+r.nextInt(5)%3
- Anonymous on Aug 6, 2012
1
of 1
vote