The Wayback Machine - https://web.archive.org/web/20240927090521/https://www.geeksforgeeks.org/print-0-and-1-with-50-probability/
Open In App

Make a fair coin from a biased coin

Last Updated : 10 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with 60% probability, and 1 with 40% probability. Write a new function that returns 0 and 1 with a 50% probability each. Your function should use only foo(), no other library method.

Solution: 
We know foo() returns 0 with 60% probability. How can we ensure that 0 and 1 are returned with a 50% probability? 
The solution is similar to this post. If we can somehow get two cases with equal probability, then we are done. We call foo() two times. Both calls will return 0 with a 60% probability. So the two pairs (0, 1) and (1, 0) will be generated with equal probability from two calls of foo(). Let us see how.
(0, 1): The probability to get 0 followed by 1 from two calls of foo() = 0.6 * 0.4 = 0.24 
(1, 0): The probability to get 1 followed by 0 from two calls of foo() = 0.4 * 0.6 = 0.24
So the two cases appear with equal probability. The idea is to return consider only the above two cases, return 0 in one case, return 1 in other case. For other cases [(0, 0) and (1, 1)], recur until you end up in any of the above two cases. 

The below program depicts how we can use foo() to return 0 and 1 with equal probability.  

C++




#include <bits/stdc++.h>
using namespace std;
 
int foo() // given method that returns 0
          // with 60% probability and 1 with 40%
{
    // some code here
}
 
// returns both 0 and 1 with 50% probability
int my_fun()
{
    int val1 = foo();
    int val2 = foo();
    if (val1 == 0 && val2 == 1)
        return 0; // Will reach here with
                  // 0.24 probability
    if (val1 == 1 && val2 == 0)
        return 1; // Will reach here with
                  // 0.24 probability
    return my_fun(); // will reach here with
                     // (1 - 0.24 - 0.24) probability
}
 
// Driver Code
int main()
{
    cout << my_fun();
    return 0;
}
 
// This is code is contributed
// by rathbhupendra


C




#include <stdio.h>
 
int foo() // given method that returns 0 with 60%
          // probability and 1 with 40%
{
    // some code here
}
 
// returns both 0 and 1 with 50% probability
int my_fun()
{
    int val1 = foo();
    int val2 = foo();
    if (val1 == 0 && val2 == 1)
        return 0; // Will reach here with 0.24 probability
    if (val1 == 1 && val2 == 0)
        return 1; // // Will reach here with 0.24
                  // probability
    return my_fun(); // will reach here with (1 - 0.24 -
                     // 0.24) probability
}
 
int main()
{
    printf("%d ", my_fun());
    return 0;
}


Java




import java.io.*;
 
class GFG {
 
    // Given method that returns 0
    // with 60% probability and 1 with 40%
    static int foo()
    {
        // some code here
    }
 
    // Returns both 0 and 1 with 50% probability
    static int my_fun()
    {
        int val1 = foo();
        int val2 = foo();
        if (val1 == 0 && val2 == 1)
 
            return 0; // Will reach here with
                      // 0.24 probability
 
        if (val1 == 1 && val2 == 0)
 
            return 1; // Will reach here with
                      // 0.24 probability
 
        return my_fun(); // will reach here with
                         // (1 - 0.24 - 0.24) probability
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        System.out.println(my_fun());
    }
}
 
// This code is contributed by ShubhamCoder


Python3




# Python3 program for the
# above approach
def foo():
   
    # Some code here
    pass
 
# Returns both 0 and 1
# with 50% probability
def my_fun():
   
    val1, val2 = foo(), foo()
     
    if val1 ^ val2:
       
        # Will reach here with
        # (0.24 + 0.24) probability
        return val1
       
    # Will reach here with
    # (1 - 0.24 - 0.24) probability
    return my_fun()
 
# Driver Code
if __name__ == '__main__':
    print(my_fun())
 
# This code is contributed by sgshah2


C#




using System;
 
class GFG {
 
    // given method that returns 0
    // with 60% probability and 1 with 40%
    static int foo()
    {
        // some code here
    }
 
    // returns both 0 and 1 with 50% probability
    static int my_fun()
    {
        int val1 = foo();
        int val2 = foo();
        if (val1 == 0 && val2 == 1)
            return 0; // Will reach here with
                      // 0.24 probability
        if (val1 == 1 && val2 == 0)
            return 1; // Will reach here with
                      // 0.24 probability
        return my_fun(); // will reach here with
                         // (1 - 0.24 - 0.24) probability
    }
 
    // Driver Code
    static public void Main() { Console.Write(my_fun()); }
}
 
// This is code is contributed
// by ShubhamCoder


PHP




<?php
 
function foo()  // given method that returns 0
                // with 60% probability and 1 with 40%
{
    // some code here
}
 
// returns both 0 and 1 with 50% probability
function my_fun()
{
    $val1 = foo();
    $val2 = foo();
    if ($val1 == 0 && $val2 == 1)
        return 0; // Will reach here with
                  // 0.24 probability
    if ($val1 == 1 && $val2 == 0)
        return 1; // Will reach here with
                  // 0.24 probability
    return my_fun(); // will reach here with
                     // (1 - 0.24 - 0.24) probability
}
 
// Driver Code
echo my_fun();
 
// This is code is contributed
// by Akanksha Rai
?>


Javascript




<script>
 
// Given method that returns 0 with
// 60% probability and 1 with 40%
function foo()
{
    // Some code here
}
 
// Returns both 0 and 1 with
// 50% probability
function my_fun()
{
    var val1 = foo();
    var val2 = foo();
     
    if (val1 == 0 && val2 == 1)
        return 0; // Will reach here with
                  // 0.24 probability
                   
    if (val1 == 1 && val2 == 0)
        return 1; // Will reach here with
                  // 0.24 probability
                   
    return my_fun(); // Will reach here with
                     // (1 - 0.24 - 0.24) probability
}
 
// Driver Code
document.write(my_fun());
 
// This code is contributed by noob2000
 
</script>


Time Complexity: O(1)

Auxiliary Space: O(1)

References: 
http://en.wikipedia.org/wiki/Fair_coin#Fair_results_from_a_biased_coin
This article is compiled by Shashank Sinha and reviewed by GeeksforGeeks team.  

 



Previous Article
Next Article

Similar Reads

Probability of getting more heads than tails when N biased coins are tossed
Given an array p[] of odd length N where p[i] denotes the probability of getting a head on the ith coin. As the coins are biased, the probability of getting a head is not always equal to 0.5. The task is to find the probability of getting heads more number of times than tails. Examples: Input: p[] = {0.3, 0.4, 0.7} Output: 0.442 Probability for a t
8 min read
Decision Trees - Fake (Counterfeit) Coin Puzzle (12 Coin Puzzle)
Let us solve the classic "fake coin" puzzle using decision trees. There are the two different variants of the puzzle given below. I am providing description of both the puzzles below, try to solve on your own, assume N = 8. Easy: Given a two pan fair balance and N identically looking coins, out of which only one coin is lighter (or heavier). To fig
12 min read
Count Fair pairs in a String with Uppercase-Lowercase operations
Given a string S of length N that contains only uppercase and lowercase letters, the task is to find the maximum number of pairs that consist of an uppercase and a lowercase version of the same letter, and each character can only belong to one pair. You are allowed to perform K operations, wherein each operation, you can either change an uppercase
9 min read
Minimizing Cost to Convert Binary String to Fair String
Given a binary string S of size N. You had been given the task of converting the given string into a Fair string. You can do the following operation any number of times : If the ith character in S is 0, replace it with 1 using cost C[i].If the ith character in S is 1, replace it with 0 using cost C[i].You have to determine the minimum cost used to
7 min read
Coin Change - Minimum Coins to Make Sum
Given an array coins[] of size N and a target value sum, where coins[i] represents the coins of different denominations. You have an infinite supply of each of coins. The task is to find minimum number of coins required to make the given value sum. If it's not possible to make a change, print -1. Examples: Input: coins[] = {25, 10, 5}, sum = 30Outp
15+ min read
Coin Change - Count Ways to Make Sum
Given an integer array of coins[ ] of size N representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = {1,2,3}Output: 4Explanation: there are four solutions: {1, 1,
15+ min read
Coin game of two corners (Greedy Approach)
Consider a two-player coin game where each player gets turned one by one. There is a row of even a number of coins, and a player on his/her turn can pick a coin from any of the two corners of the row. The player that collects coins with more value wins the game. Develop a strategy for the player making the first turn, such that he/she never loses t
9 min read
Probability of getting two consecutive heads after choosing a random coin among two different types of coins
Given two coins which have probability of getting heads p% and q% respectively, the task is to determine the probability of getting two consecutive heads after choosing random coins among the given coins.Examples: Input: p = 33, q = 66 Output: 0.550000000000000Input: p = 33, q = 66 Output: 0.550000000000000 Approach: Since both the coins are not id
5 min read
Predict the winner in Coin Game
There are two players P1 and P2 and two piles of coins consisting of M and N coins respectively. At each turn, a player can choose only one of the piles out of these and discard the other one. This discarded pile cannot be used further in the game. The pile player chooses is further divided into two piles of non-zero parts. The player who cannot di
4 min read
Coin Change | BFS Approach
Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4} Output: 2 The minimum number elements will be 2 as
6 min read
Find the player who will win the Coin game
Given N coins, the task is to find who win the coin game.Coin game is a game in which each player picks coins from the given N coins in such a way that he can pick coins ranging from 1 to 5 coins in one turn and the game continues for both the players. The player who picks the last coin loses the game.Examples: Input: N = 4 Output: First Player Exp
4 min read
Probability of not getting two consecutive heads together in N tosses of coin
Given a fair coin that is tossed N times, the task is to determine the probability such that no two heads occur consecutively. Examples: Input: N = 2 Output: 0.75 Explanation: When the coin is tossed 2 times, the possible outcomes are {TH, HT, TT, HH}. Since in 3 out of 4 outcomes, heads don't occur together. Therefore, the required probability is
8 min read
Probability of getting K heads in N coin tosses
Given two integers N and R. The task is to calculate the probability of getting exactly r heads in n successive tosses. A fair coin has an equal probability of landing a head or a tail on each toss. Examples: Input : N = 1, R = 1 Output : 0.500000 Input : N = 4, R = 3 Output : 0.250000 Approach Probability of getting K heads in N coin tosses can be
4 min read
Count of total Heads and Tails after N flips in a coin
Given character C and an integer N representing N number of coins in C position where C can be either head or tail. We can flip the coins N times, wherein the ith round the player will flip the face of all the coins whose number is less than or equal to i. The task is to determine the total number of head and tail after flipping N possible times. E
6 min read
Minimum moves taken to move coin of each cell to any one cell of Matrix
Given an odd number N which represents a grid of size N x N which is initially filled by coins, the task is to find the minimum number of moves required for all the coins to move to any cell of the grid such that in each step, some arbitrary coin in the middle of the grid can move to any of the surrounding eight cells. Examples: Input: N = 3 Output
6 min read
Philaland Coin | TCS Mockvita 2020
Problem Description The problem solvers have found a new Island for coding and named it as Philaland. These smart people were given a task to make purchase of items at the Island easier by distributing various coins with different value. Manish has come up with a solution that if we make coins category starting from $1 till the maximum price of ite
4 min read
Count ways to distribute exactly one coin to each worker
Given two arrays coins[] and salaries[] where coins[i] represents the value of ith coin and salaries[j] represents the minimum value of the coin that jth worker will accept. The task is to compute the number of ways to distribute exactly one coin to each worker. Since the answer can be large, print it modulo 109 + 7.Examples: Input: coins[] = {1, 2
6 min read
Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other
Given two piles of coins consisting of N and M coins, the task is to check if both the piles can be emptied simultaneously by repeatedly removing 2 coins from one pile and 1 coin from the other pile. If both the piles can be made empty, then print "Yes". Otherwise, print "No". Examples: Input: N = 1, M = 2 Output: Yes Explanation: Remove 1 coin fro
6 min read
Maximum coin in minimum time by skipping K obstacles along path in Matrix
Given a 2D matrix, where '*' represents an obstacle and the rest all represent coins in the grid. It is also given that you are currently on grid[i1][ j1] and want to reach grid[i2][j2] by skipping at most K obstacles in the path, the task is to collect the maximum coin while reaching grid[i2][j2] in a minimum amount of time. Note: Only movements i
14 min read
Frobenius coin problem
Given two coins of denominations "X" and "Y" respectively, find the largest amount that cannot be obtained using these two coins (assuming an infinite supply of coins) followed by the total number of such non-obtainable amounts, if no such value exists print "NA". Examples : Input : X=2, Y=5 Output: Largest amount = 3 Total count = 2 We cannot repr
7 min read
Minimum cost for acquiring all coins with k extra coins allowed with every coin
You are given a list of N coins of different denominations. You can pay an amount equivalent to any 1 coin and can acquire that coin. In addition, once you have paid for a coin, we can choose at most K more coins and can acquire those for free. The task is to find the minimum amount required to acquire all the N coins for a given value of K. Exampl
11 min read
Coin game winner where every player has three choices
A and B are playing a game. In the beginning, there are n coins. Given two more numbers x and y. In each move, a player can pick x or y or 1 coin. A always starts the game. The player who picks the last coin wins the game or the person who is not able to pick any coin loses the game. For a given value of n, find whether A will win the game or not i
8 min read
CSES Solutions - Missing Coin Sum
You have N coins with positive integer values. What is the smallest sum you cannot create using a subset of the coins? Examples: Input: N = 5, coins[] = {2, 9, 1, 2, 7}Output: 6Explanation: Sum = 1, we can take the coin with value 1.Sum = 2, we can take the coin with value 2.Sum = 3, we can take coins with value 1 and 2.Sum = 4, we can take coins w
6 min read
CSES Solutions - Coin Piles
You are given Q queries. In each query, you have two coin piles containing A and B coins. On each move, you can either remove one coin from the left pile and two coins from the right pile, or two coins from the left pile and one coin from the right pile. Your task is to efficiently find out if you can empty both the piles. Examples: Input: Q = 3, q
7 min read
CSES Solutions - Coin Combinations I
Consider a money system consisting of N coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ways you can produce a money sum X using the available coins. Examples: Input: N = 3, X = 9, coins[] = {2, 3, 5}Output: 8Explanation: There are 8 number of ways to make sum = 9. {2, 2, 5} = 2 + 2 + 5 = 9{2, 5, 2} =
8 min read
Expected number of coin flips to get two heads in a row?
What is Probability?Probability is the measure of the likelihood that an event will occur. It is quantified as a number between 0 and 1, where 0 indicates impossibility and 1 indicates certainty. Problem Statement: Find the expected number of coin flips required to get two heads consecutively.Solution:   Let x be the expected number of coin flips n
1 min read
CSES Solutions - Coin Combinations II
Consider a money system consisting of N coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ordered ways you can produce a money sum X using the available coins. Examples: Input: N = 3, X = 9, coins[] = {2, 3, 5}Output: 3Explanation: There are three ways to produce money sum of 9. Coins {2, 2, 5}, sum = 2
8 min read
Coin change problem with limited coins
Given three integers n, k, target, and an array of coins[] of size n. Find if it is possible to make a change of target cents by using an infinite supply of each coin but the total number of coins used must be exactly equal to k. Examples: Input: n = 5, k = 3, target = 11, coins = {1, 10, 5, 8, 6}Output: 1Explanation: 2 coins of 5 and 1 coin of 1 c
12 min read
Find if it is possible to make a binary string which contains given number of "0", "1" , "01" and "10" as sub sequences
Given four integers l, m, x, and y. The task is to check whether it is possible to make a binary string consisting of l 0's, m 1's, x "01" and y "10" as sub-sequences in it.Examples: Input: l = 3, m = 2, x = 4, y = 2 Output: Yes Possible string is "00110". It contains 3 0's, 2 1's, 4 "01" sub-sequences and 2 "10" sub-sequences.Input: l = 3, m = 2,
4 min read
Print digit's position to be removed to make a number divisible by 6
Given a number N, remove exactly one digit to make the number divisible by 6 (make it the largest possible). Print the position that has to be removed, If not possible then print -1. Examples: Input: 123 Output: 3 Explanation: Remove 3rd position element and hence the number is 12, which is divisible by 6 and is the greatest possible. Input: 134 Ou
15 min read
Article Tags :
Practice Tags :