Toss Strange Coins in C++


Suppose we have some coins. The i-th coin has a probability prob[i] of facing heads when tossed. We have to show the probability that the number of coins facing heads equals target if you toss every coin exactly once. So if the prob array is like [0.5,0.5,0.5,0.5,0.5] and target is 0, then the output will be 0.03125.

To solve this, we will follow these steps −

  • n := size of prob array
  • create one 2d array of size n x (target + 5)
  • set dp[0,0] = 1 – prob[0] and dp[0,1] := prob[0]
  • for i in range 1 to n – 1
    • dp[i, 0] := (1 – prob[i]) * dp[i – 1, 0]
    • for j in range 1 to minimum of i + 1 and target
      • dp[i, j] := (1 – prob[i]) * dp[i – 1, j] + prob[i]*dp[i – 1, j - 1]
  • return dp[n – 1, target]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   double probabilityOfHeads(vector<double>& prob, int target) {
      int n = prob.size();
      vector < vector <double> > dp(n, vector <double>(target+5));
      dp[0][0] = 1- prob[0];
      dp[0][1] = prob[0];
      for(int i =1;i<n;i++){
         dp[i][0] = (1-prob[i])*dp[i-1][0];
         for(int j =1;j<=min(i+1,target);j++){
            dp[i][j] = (1-prob[i])*dp[i-1][j] + prob[i]*dp[i-1][j-1];
         }
      }
      return dp[n-1][target];
   }
};
main(){
   vector<double> v = {0.5,0.5,0.5,0.5,0.5};
   Solution ob;
   cout << (ob.probabilityOfHeads(v, 0));
}

Input

[0.5,0.5,0.5,0.5,0.5]
0

Output

0.03125

Updated on: 30-Apr-2020

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements