Created
December 20, 2023 10:20
-
-
Save LorisSigrist/ed5d7545e7e800231965dc6230193474 to your computer and use it in GitHub Desktop.
Birthday Problem simulation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const num_days = 16_000_000; | |
const num_participants = 100_000; | |
const samples = 100_000; | |
let collisions = 0; | |
const percentageFormatter = new Intl.NumberFormat('en-US', { | |
style: 'percent', | |
maximumFractionDigits: 3, | |
}); | |
for (let i = 0; i < samples; i++) { | |
const birthdays = new Set(); | |
for (let j = 0; j < num_participants; j++) { | |
const birthday = Math.floor(Math.random() * num_days); | |
if (birthdays.has(birthday)) { | |
collisions++; | |
break; | |
} | |
birthdays.add(birthday); | |
} | |
if ((i + 1) % 1000 === 0) { | |
console.log(`Sample ${i + 1} out of ${samples} - ${collisions} collisions so far (${percentageFormatter.format(collisions / (i + 1))})`); | |
} | |
} | |
console.log(`Collision probability: ${percentageFormatter.format(collisions / samples)} (sample size: ${samples})`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment