Generate fair results from a biased coin that prefers one side of the coin over another and returns TAILS with p probability and HEADS with 1-p probability where p != (1-p).

Practice this problem

We can use the given biased coin for fair results by making two calls from the biased coin instead of one call. If the results of both calls match (both are HEADS, or both are TAILS), discard the results and start over. If the results differ, consider the first result.

How this works?

Suppose we have a biased() function that returns TAILS with p probability and HEADS with 1-p probability. We make two independent subsequent calls to the biased() and store the results. Then there are four possible possibilities:

  1. The probability that both calls returns TAILS = p × p
  2. The probability that both calls returns HEADS = (1 - p) × (1 - p)
  3. The probability that the first call returns TAILS, and the second call returns HEADS = p × (1 - p)
  4. The probability that the first call returns HEADS, and the second call returns TAILS = (1 - p) × p

Clearly, the biased coin has the same probability of getting TAILS and then HEADS as the probability of getting HEADS and then TAILS. So if we exclude the events of two HEADS and two TAILS by repeating the procedure, we are left with the only two remaining outcomes having equivalent probability. That’s the reason why we will get a fair result.

 
Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

References: https://en.wikipedia.org/wiki/Fair_coin#Fair_results_from_a_biased_coin