📜  在给定击中目标的概率时,求玩家获胜的概率

📅  最后修改于: 2021-09-24 05:00:22             🧑  作者: Mango

给定四个整数pqrs 。两个玩家正在玩一个游戏,其中玩家都击中了目标,第一个击中目标的玩家赢得了比赛。第一个玩家击中目标的概率为p / q ,第二个玩家击中目标的概率为r / s 。任务是找出第一个玩家赢得比赛的概率。

例子:

方法:第一个玩家击中目标的概率为p / q ,未命中目标的概率为1 – p / q
第二个玩家击中目标的概率为r / s ,而未命中目标的概率为1 – r / s
让第一个玩家是x ,第二个玩家是y
所以总概率将是x 赢 + (x 输了 * y 输了 * x 赢了) + (x 输了 * y 输了 * x 输了 * y 输了 * x 赢了) + …等等
因为x可以在任何回合获胜,所以这是一个无限序列。
t = (1 – p / q) * (1 – r / s) 。这里t < 1作为p / qr / s总是<1
所以级数会变成, p / q + (p / q) * t + (p / q) * t 2 + …
这是一个公比小于 1 的无限 GP 级数,其总和为(p / q) / (1 – t)

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the probability of the winner
double find_probability(double p, double q,
                        double r, double s)
{
 
    double t = (1 - p / q) * (1 - r / s);
 
    double ans = (p / q) / (1 - t);
 
    return ans;
}
 
// Driver Code
int main()
{
    double p = 1, q = 2, r = 1, s = 2;
 
    // Will print 9 digits after the decimal point
    cout << fixed << setprecision(9)
         << find_probability(p, q, r, s);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
import java.text.DecimalFormat;
 
class solution
{
 
// Function to return the probability of the winner
static double find_probability(double p, double q,
                        double r, double s)
{
 
    double t = (1 - p / q) * (1 - r / s);
 
    double ans = (p / q) / (1 - t);
 
    return ans;
}
 
// Driver Code
public static void main(String args[])
{
    double p = 1, q = 2, r = 1, s = 2;
 
    // Will print 9 digits after the decimal point
    DecimalFormat dec = new DecimalFormat("#0.000000000");
    System.out.println(dec.format(find_probability(p, q, r, s)));
}
}
// This code is contributed by
// Surendra_Gangwar


Python3
# Python3 implementation of the approach
 
# Function to return the probability
# of the winner
def find_probability(p, q, r, s) :
     
    t = (1 - p / q) * (1 - r / s)
 
    ans = (p / q) / (1 - t);
 
    return round(ans, 9)
 
# Driver Code
if __name__ == "__main__" :
 
    p, q, r, s = 1, 2, 1, 2
 
    # Will print 9 digits after
    # the decimal point
    print(find_probability(p, q, r, s))
 
# This code is contributed by Ryuga


C#
// C# mplementation of the approach
using System;
 
class GFG
{
 
// Function to return the probability of the winner
static double find_probability(double p, double q,
                        double r, double s)
{
 
    double t = (1 - p / q) * (1 - r / s);
 
    double ans = (p / q) / (1 - t);
 
    return ans;
}
 
// Driver Code
public static void Main()
{
    double p = 1, q = 2, r = 1, s = 2;
    Console.WriteLine(find_probability(p, q, r, s));
}
}
 
// This code is contributed by
// anuj_67..


PHP


Javascript


输出:
0.666666667

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程