I came across this reported interview question when doing some reviewing (the following quote is all the info I found about the problem):
Given a function for a fair coin, write a function for a biased coin that returns heads 1/n times (n is a param)
At first glance I wrote:
int biased_coin(n) { //0=Tails, 1=Heads
int sum = 0;
if(n==1)
return 1;
for(int i=0;i<n;i++) {
sum += unbiased(); //unbiased returns 0 50% of the time and 1 50% of the time
}
if(sum == 1)
return 1;
return 0;
}
But this obviously doesn't work. For n=4, for instance, it does work: since the probability of getting a single Head given 4 tosses is 4/(2^4)=1/4. But for say n=3, 3/(2^3)!=1/3.
What is the proper way to implement something like this assuming you can't use a random number generator?