Tuesday, August 18, 2020

Day 4: Binomial Distribution I Solution | HackerRank | Statistics

 

Task
The ratio of boys to girls for babies born in Russia is . If there is  child born per birth, what proportion of Russian families with exactly  children will have at least  boys?

Write a program to compute the answer using the above parameters. Then print your result, rounded to a scale of  decimal places (i.e.,  format).

Input Format

A single line containing the following values:

1.09 1

If you do not wish to read this information from stdin, you can hard-code it into your program.

Output Format

Print a single line denoting the answer, rounded to a scale of  decimal places (i.e.,  format).


Problem Solution in C++ Programming Language:

code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iomanip>

using namespace std;

int fact(int n){
    if(n == 1 || n == 0)
        return 1;
    return (n * fact(n-1));
}
double binomial_dist(int x , int n , float p){
    int f = fact(n) / (fact(x)*fact(n-x)) ;
    double powers = pow(p,x) * (pow((1-p),(n-x)));
    return f * powers;
}
int main() {
     cout << setprecision(3) << fixed << (binomial_dist(3,6,(1.09/2.09)) +
     binomial_dist(4,6,(1.09/2.09)) + binomial_dist(5,6,(1.09/2.09)) 
    + binomial_dist(6,6,(1.09/2.09))) ;
    return 0;
}



Problem Solution in Java Programming Language:

code:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double M = sc.nextDouble();
        double F = sc.nextDouble();
        double pb = M / (M+F);
        double pg = F / (M+F);
        double p3b = 0;
        for (int i = 0; i < (1<<6); i++) {
            int boys = 0;
            double p = 1;
            for (int j = 0; j < 6; j++) {
                boolean isBoy = (i & (1<<j)) != 0;
                p *= isBoy ? pb : pg;
                if (isBoy) boys++;
            }
            if (boys >= 3) {
                p3b += p;
            }
        }
        System.out.println(Math.round(1000 * p3b) / 1000d);
    }
}



Problem Solution in Python Programming Language:

code:

# Enter your code here. Read input from STDIN. Print output to STDOUT
def fact(n):
    return 1 if n == 0 else n*fact(n-1)

def comb(n, x):
    return fact(n) / (fact(x) * fact(n-x))

def b(x, n, p):
    return comb(n, x) * p**x * (1-p)**(n-x)

l, r = list(map(float, input().split(" ")))
odds = l / r
print(round(sum([b(i, 6, odds / (1 + odds)) for i in range(3, 7)]), 3))




Thank you for your visit. Keep coding! 



No comments:

Post a Comment

Please do not enter any spam link in the comment box