Compute the probability of a Republican majority
House_majority.cpp HouseMajority.javapublic static double houseMajority(double[] prob, int n) {
// Initializes DP table.
double[][] P = new double[n + 1][n + 1];
for (double[] element : P) {
Arrays.fill(element, -1.0);
}
// Accumulates the probabilities of majority cases.
double probSum = 0.0;
for (int r = (int) ceil(0.5 * n); r <= n; ++r) {
probSum += houseMajorityHelper(prob, r, n, P);
}
return probSum;
}
// prob is the probability that each Republican wins.
// r is the number of Republicans wins, and n is the number of elections.
private static double houseMajorityHelper(double[] prob, int r, int n,
double[][] P) {
if (r > n) {
return 0.0; // Base case: not enough Republicans.
} else if (r == 0 && n == 0) {
return 1.0; // Base case.
} else if (r < 0) {
return 0.0;
}
if (P[r][n] == -1.0) {
P[r][n] = houseMajorityHelper(prob, r - 1, n - 1, P) * prob[n - 1]
+ houseMajorityHelper(prob, r, n - 1, P) * (1.0 - prob[n - 1]);
}
return P[r][n];
}