Amazon.com
3.4 of 5 2,804 reviews
www.amazon.com Seattle, WA 5000+ Employees

Amazon.com Senior Software Engineer Interview Question

I interviewed in Beijing, Beijing (China) and was asked:
"Rand(7) from Rand(5)"
Add Tags [?]
Answer Flag Question

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

Answers & Comments

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

int RandBin()
{

}
- David on Oct 25, 2011 Flag Response
3
of 4
votes
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 Flag Response
2
of 2
votes
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 Flag Response
0
of 0
votes
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 Flag Response
0
of 1
vote
Java:
Random r = new Random();
r.nextInt(5)+r.nextInt(5)%3
- Anonymous on Aug 6, 2012 Flag Response
1
of 1
vote
what about calling rand(5) 7 times adding it then % 7
( rand5() + rand5() + rand 5() + rand5() + rand5 () + rand5() + rand5() ) % 7

-suhane
- ravi on Nov 20, 2012 Flag Response

To comment on this question, Sign In with Facebook or Sign Up


Tags are like keywords that help categorize interview questions that have something in common.

Glassdoor is your free inside look at Amazon.com interview questions and advice. All interview reviews posted anonymously by Amazon.com employees and interview candidates.