Find probability that a player wins when probabilities of hitting the target are given in C++



In this problem we are given four values p, q, r, s. Our task is to Find probability that a player wins when probabilities of hitting the target are given.

Here, we have two players who are playing a game of archery. And the probability of player 1 hitting the target is defined as p/q. The probability of player 2 hitting the target is defined as r/s. We need to find the probability of player one winning the game.

Let’s take an example to understand the problem,

Input

p = 3, q = 5, r = 2, s = 5

Output

0.789

Solution Approach

*This approach requires the knowledge of probability.

Since, there is no upper limit to the number of times the players can get the chance to hit the target. Both can hit the target any number of times which makes the winning situation calculation independ to the number of trials.

So,

Let's say the probability of player one hitting the target is P1 = p/q, this makes the probability of missing 1 - p/q.

Let's say the probability of player two hitting the target is P2 = r/s, which makes the probability of missing 1 - r/s.

Now, for infinite number of trials, the probability of player 1 winning can be,

000win(P1) + (lost(P1)*lost(P2)*win(P1)) +
(lost(P1)*lost(P2)*lost(P1)*lost(P2)*win(P1) + ….

Which can be formulated as,

P1 + ((1 - P1)*(1 - P2)*(P1)) + ((1 - P1)*(1 - P2)*(1 - P1)*(1 - P2)*(P1)) …

This is an infinite GP where,

A = P1
R = [(1 - P1)*(1 - P2)]

The sum will be,

S = A/ (1- R) , as R is less than 1.

$$S=\left(\frac{\left(\frac{p}{p}\right)}{1-\left(1-\frac{p}{p}\right)*\left(1-\frac{p}{p}\right)}\right)$$

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
double calcWinningPropP1(double p, double q, double r, double s){
   return (p / q) / (1 - ( (1 - (p/q)) * (1 - (r/s)) ) );
}
int main() {
   double p = 3, q = 5, r = 2, s = 5;
   cout<<"The probability of player 1 winning is "<<calcWinningPropP1(p, q, r, s);
   return 0;
}

Output

The probability of player 1 winning is 0.789474

Advertisements