Cleaning environment and console

rm(list=ls())

Creating function

set.seed(1)
n <- 23
match <- 0

# Simulate 10000 rooms and check for matches in each room
for(i in 1:10000){
  
  birthdays <- sample(c(1:365), size = n, replace = TRUE)
  
  if(length(unique(birthdays)) < n)
  {
    match <- match + 1
  } 
}

Evaluating probabilities

p_match = match/10000
p_match
## [1] 0.5026

But wait there is an inbuilt functions called “pbirthday” against which we can confirm our simulation approach.

pbirthday(50)
## [1] 0.9703736

#Plotting probabilities

room_size = c(1:50)
matching_prob = sapply(room_size,pbirthday)
plot(matching_prob ~ room_size)