Amazon Interview Question
Software Engineer / Developersint fun(int a,int b)
{
int x=0;
while(b)
{
b=b>>1;
x++;
}
return utility(a,b,x);
}
int utility(int a,int b,int x)
{
int y=0;
for(int i=0;i<x;i++)
{
y=y|random();
y=y<<1;
}
if(y>=b)
return utility(a,b,x);
else if(y<a)
return 0;
else
return 1;
}
This is how I will implement it:
Take the greater of two numbers in this case b. Generate a random no between range [1,b] if this no is less than equal to a then output heads else output tails. So, if choose a = 5 and b =7 generate no between 1 and 7. If no is less than equal to 5 output heads. The probability of generating heads here is 5/7 i.e. a/b and probability of generating tails is 2/7 i.e. (b-a)/b
This is how I will implement it:
Take the greater of two numbers in this case b. Generate a random no between range [1,b] if this no is less than equal to a then output heads else output tails. So, if choose a = 5 and b =7 generate no between 1 and 7. If no is less than equal to 5 output heads. The probability of generating heads here is 5/7 i.e. a/b and probability of generating tails is 2/7 i.e. (b-a)/b
Yes, Erik's solution does the same thing.
If you noticed, we are only given a _fair_ coin, i.e 1 with pbt 1/2 and 0 with pbt 1/2. So the statement "I will generate a random number in {1,2,..,b}" needs to make use of the fact that the only source of randomness you have is a fair coin.
What Erik is doing is to generate [log b] random bits of a number. If that number (as represented in binary by those bits) is greater than b, he tries again.
if that number is <= b and <=a , then it is heads, else if that number > a and <=b, it is tails.
I did not see the other solution just proposed how I think it can be done but thanks for the explanation
I'm not sure if I understand the problem fully, bit is this sufficient?
int unevenRand (unsigned int a, unsigned int b)
{
unsigned int number;
rand_s(&number);
number = number%(b);
if (number <a)
return 1;
else
return 0;
}
i think Ericks solution is the simplest one also gaurav.18 explanation says he is doing the same thing. that it... very nice question and nicely answered by Eric. Thanks Erick.
anyone got the solution?
- Andy July 20, 2009