Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save evan-goode/fcb1028827a638415c0e8ed608131e68 to your computer and use it in GitHub Desktop.
Save evan-goode/fcb1028827a638415c0e8ed608131e68 to your computer and use it in GitHub Desktop.
a bad way to calculate probabilities
p Calculates the probability of the occurence of one or more events in a set (#[i P(A∪B∪C...)]).
p Enter probabilities, #[i 0 < P(X) < 1], separated by commas.
input#input
button#go Go
br
pre#result
document.querySelector("#go").addEventListener("click", function() {
document.querySelector("#result").textContent = or(JSON.parse("[" + document.querySelector("#input").value + "]"))
})
function or (array) {
var probability = 0
var combos = []
for (var i = 1; i < array.length + 1; i++) {
var combinations = getCombinations(array, i)
for(var j = 0; j < combinations.length; j++) {
combos.push(combinations[j])
}
}
for (var i = 0; i < combos.length; i++) {
product = combos[i][0]
for(var j = 1; j < combos[i].length; j++) {
product *= combos[i][j]
}
if(combos[i].length % 2 == 0) {
probability -= product
} else {
probability += product
}
}
return probability
}
function getCombinations (array, k) {
if (k > array.length || k <= 0) {
return []
}
if (k == array.length) {
return [array]
}
if (k == 1) {
var combinations = []
for(i = 0; i < array.length; i++) {
combinations.push([array[i]]);
}
return combinations;
}
combinations = [];
for (var i = 0; i < array.length - k + 1; i++) {
var head = array.slice(i, i + 1);
var tail = getCombinations(array.slice(i + 1), k - 1);
for (var j = 0; j < tail.length; j++) {
combinations.push(head.concat(tail[j]));
}
}
return combinations;
}
/*
I now realize this is dumb and you can just take 1 - P(A' ∩ B' ∩ C'). Oh well.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment