xxxxxxxxxx
38
/*
This program uses a brute force approach to solve the
birthday problem, which asks for the number of people that must
be in a room so that it's more likely than not that at least
two of the people share a birthday, in this case assuming 365
days in a year and a uniform distribution of birthdays througout the year.
The code is intended to be easily understood from
basic mathematical notions and programming concepts, and for
the problem above with a shared birthday probability > 1 / 2,
this code is sufficient. However, it may hit computational
limits if this threshold probability of 1 / 2
is replaced with 0.9999999999 or greater; in that case,
it may give incorrect results.
NOTE:
We could also compute p as
1 - (product from k = 0 to n - 1 of (1 - k / 365)).
*/
//r^(k falling) = r * (r-1) * ... * (r - (k-1))
function falling(r, k) {
let power = 1;
for (let i = 0; i < k; i++) {
power *= r - i;
}
return power;
}
let p; //probability of a collision
let pThreshold = 0.5; //threshold probability
let n = 1; //number of people
do {
p = 1 - falling(365, n) / 365 ** n;
console.log(`n = ${n}: ${p}`);
n++;
} while (p <= pThreshold)