R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Birthday Probability}

The Question

How many students need to be in a class such that at least two students share the same birthday?

 

For birthday, we mean day of the year e.g. March 4th

Approach

  • We can use Monte Carlo simulation to determine the answer
  • Monte Carlo simulation works by repeatedly sampling to obtain numerical results
  • For each sample we generate random birthdays (i.e. numbers between 0 and 364) until two birthdays are the same
  • The number of birthdays we generate in each sample equals the number of students in the class for that sample
  • We repeat each sample X number of times and then determine the average number of birthdays over all samples
function birthdayProbability(numSimulations){
    var numStudents = 0;
    
    for(let i = 0; i < numSimulations; i++){
        let studentsBday = [];
        
        do{
            studentsBday.push(Math.round(Math.random()*364));
            var index = studentsBday.indexOf(studentsBday[studentsBday.length - 1]);
        }while(index === studentsBday.length - 1)
        
        numStudents += studentsBday.length;
    }
    
    return Math.ceil(numStudents / numSimulations);
}

birthdayProbability(10000); 
//we can repeat the simulations until the solution is stable
//here we arbitrarily select a sample size of 10,000

Solution

Solution

Birthday Probability

By pat310

Birthday Probability

Technical interview problem to determine how many students need to be in the class such that two students share the same birthday.

  • 1,506