Source : https://www.hackerrank.com/challenges/s10-binomial-distribution-1
Objective
In this challenge, we learn about binomial distributions. Check out the Tutorial tab for learning materials!
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).
Source : https://www.hackerrank.com/challenges/s10-binomial-distribution-1
Solution
// github.com/RodneyShag | |
public class Solution { | |
public static void main(String[] args) { | |
double ratio = 1.09; // hardcoded value | |
double p = ratio / (1 + ratio); | |
int n = 6; | |
/* Calculate result */ | |
double result = 0; | |
for (int x = 3; x <= n; x++) { | |
result += binomial(n, x, p); | |
} | |
System.out.format("%.3f", 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