Skip to main content

Convert Biased Coin to Fair Coin

MediumPremium

Given a biased coin function, write another function to make it return heads or tails with equal probability.

You are given a function biased_coin() that simulates the flip of a biased coin. The function returns 1 for heads and 0 for tails with unequal probabilities. Specifically, the probability of returning heads (1) is p, and the probability of returning tails (0) is 1 - p, where p is not necessarily 0.5.

Your task is to write a new function fair_coin() that uses biased_coin() to simulate a fair coin flip. The function fair_coin() should return 1 for heads and 0 for tails with equal probability (0.5 each).

Python
def fair_coin() -> int: pass

Requirements:

  1. Use biased_coin(): You must use the biased_coin() function to implement fair_coin(). You cannot use any other random number generators or external libraries.

  2. Uniform Probability: Ensure that the fair_coin() function returns 1 and 0 with exactly equal probability.

  3. Efficiency: Aim for an efficient implementation. While there is no strict constraint on the time complexity, avoid excessive or unnecessary computations.

  4. Edge Cases: Consider edge cases such as very low or very high values of p. Ensure that your solution handles these cases correctly.