Win-the-Game

Two friends Kunal and Satyam are playing an interesting game. They take turns drawing a ball from a bag that initially contains R red balls and G green balls. Each player draws a ball alternatively and never puts it back. The person who is the first to draw a red ball wins. Satyam always draws first. If there are no more balls in the bag and nobody has drawn a red ball, the Satyam wins.

What is the probability of Satyam winning?

Example:

Input:  r = 2, g = 1
Output: 0.666667

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void winTheGame(int rint g)
{

    if (r == 0)
        cout << 1.000000 << "\n";
    else
    {

        double c = 1.0ans = 0.0n = r + g;
        while (r > 0 && g >= 0 && n > 0)
        {
            ans += c * r / n;
            c *= (g) * (g - 1) / ((n - 1) * n);
            g = g - 2;
            n = n - 2;
        }
        cout << fixed << setprecision(6<< ans << "\n";
    }
}
int main()
{

    int r = 2g = 1;

    winTheGame(rg);
    return 0;
}


No comments:

Post a Comment