Source : https://www.hackerrank.com/challenges/s10-geometric-distribution-2
Objective
In this challenge, we go further with geometric distributions. We recommend reviewing the Geometric Distribution tutorial before attempting this challenge.
Task
The probability that a machine produces a defective product is . What is the probability that the defect is found during the first inspections?
Input Format
The first line contains the respective space-separated numerator and denominator for the probability of a defect, and the second line contains the inspection we want the probability of the first defect being discovered by:
1 35
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-geometric-distribution-2
Solution
// github.com/RodneyShag | |
import java.util.Scanner; | |
public class Solution { | |
public static void main(String[] args) { | |
/* Save input */ | |
Scanner scan = new Scanner(System.in); | |
int numerator = scan.nextInt(); | |
int denominator = scan.nextInt(); | |
int n = scan.nextInt(); | |
scan.close(); | |
/* Geometric Series */ | |
double p = (double) numerator / denominator; | |
double result = 0; | |
for (int i = 1; i <= 5; i++) { | |
result += geometric(i, p); | |
} | |
System.out.format("%.3f", result); | |
} | |
private static double geometric (int n, double p) { | |
return Math.pow(1 - p, n - 1) * p; | |
} | |
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