Source : https://www.hackerrank.com/challenges/s10-binomial-distribution-2
Objective
In this challenge, we go further with binomial distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.
Task
A manufacturer of metal pistons finds that, on average, of the pistons they manufacture are rejected because they are incorrectly sized. What is the probability that a batch of pistons will contain:
- No more than rejects?
- At least 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 10If 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:
- The first line should contain the probability that a batch of pistons will contain no more than rejects.
- The second line should contain the probability that a batch of pistons will contain at least rejects.
Round both of your answers to a scale of decimal places (i.e., format).
Source : https://www.hackerrank.com/challenges/s10-binomial-distribution-2
Solution
| // github.com/RodneyShag | |
| public class Solution { | |
| public static void main(String[] args) { | |
| /* Values given in problem statement */ | |
| double p = 0.12; | |
| int n = 10; | |
| /* "No more than 2 rejects" */ | |
| double result = 0; | |
| for (int x = 0; x <= 2; x++) { | |
| result += binomial(n, x, p); | |
| } | |
| System.out.format("%.3f%n", result); | |
| /* "At least 2 rejects" */ | |
| result = 1 - binomial(n, 0, p) - binomial(n, 1, p); | |
| System.out.format("%.3f%n", result); | |
| } | |
| private static Double binomial(int n, int x, double p) { | |
| if (p < 0 || p > 1 || n < 0 || x < 0 || x > n) { | |
| return null; | |
| } | |
| return combinations(n, x) * Math.pow(p, x) * Math.pow(1 - p, n - x); | |
| } | |
| private static Long combinations(int n, int x) { | |
| if (n < 0 || x < 0 || x > n) { | |
| return null; | |
| } | |
| return factorial(n) / (factorial(x) * factorial(n - x)); | |
| } | |
| private static Long factorial(int n) { | |
| if (n < 0) { | |
| return null; | |
| } | |
| long result = 1; | |
| while (n > 0) { | |
| result *= n--; | |
| } | |
| return result; | |
| } | |
| } |
No comments:
Post a Comment