# 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 and dp[0,1] := prob
• 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 = 1- prob;
dp = prob;
for(int i =1;i<n;i++){
dp[i] = (1-prob[i])*dp[i-1];
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;
}
[0.5,0.5,0.5,0.5,0.5]
0
0.03125