Day 4: Binomial Distribution II | 10 Days Of Statistics | HackerRank Solution

Hello coders, today we are going to solve Day 4: Binomial Distribution II HackerRank Solution which is a Part of 10 Days of Statistics Series.

Day 4: Binomial Distribution II

Objective

In this challenge, we go further with binomial distributions.

Task

A manufacturer of metal pistons finds that, on average, 12% of the pistons they manufacture are rejected because they are incorrectly sized. What is the probability that a batch of 10 pistons will contain:

  1. No more than 2 rejects?
  2. At least 2 rejects?

Input Format

A single line containing the following values (denoting the respective percentage of defective pistons and the size of the current batch of pistons):

12 10

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

Output Format

Print the answer to each question on its own line:

  1. The first line should contain the probability that a batch of 10 pistons will contain no more than 2 rejects.
  2. The second line should contain the probability that a batch of 10 pistons will contain at least 2 rejects.

Round both of your answers to a scale of 3 decimal places (i.e., 1.234 format).

Solution – Binomial Distribution II

C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int fact(int n)
{
    if(n<2) return 1;
    return n*fact(n-1);
}

double nCr(int n, int r)
{
    return fact(n)/(fact(r)*fact(n-r));
}

double binomial(int p, int q)
{
    return pow(0.12, double(p))*pow(0.88, double(q));
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
       
    double ans1 = 0.0, ans2 = 1.0;
    
    for(auto i=2; i>=0; i--)
    {
        ans1 += nCr(10, i)*binomial(i, 10-i);
    }
    for(auto i=1; i>=0; i--)
    {
        ans2 -= nCr(10, i)*binomial(i, 10-i);
        //ans2 = 1.0 - ans2;
    }
    printf("%0.3f\n%0.3f", ans1, ans2);
    
    return 0;
}

Disclaimer: The above Problem (Binomial Distribution II) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *