[1] 1 2 3 4 5 6 7 8 9 10
[1] 3
Problem: 10 people are at a party, and all of them are wearing hats. They each place their hat in a pile; when they leave, they choose a hat at random. What is the probability at least one person selected the correct hat?
Question: Work with your neighbor to discuss the following question:
hats
is a vector, containing the numbers 1 to 10 [1] 1 2 3 4 5 6 7 8 9 10
[1] 8 2 4 5 9 7 1 10 3 6
sample
function creates a random sample from a vectorA for
loop repeats code many times:
A for
loop repeats code many times:
A for
loop repeats code many times:
nsim <- 10000 # number of simulations
hats <- 1:10
results <- rep(NA, nsim) # vector to store results
for(i in 1:nsim){
randomized_hats <- sample(hats, size = 10, replace = FALSE)
results[i] <- sum(hats == randomized_hats) > 0
}
mean(results)
[1] 0.6373
Without magic numbers:
nsim <- 10000 # number of simulations
M <- 10 # number of people
hats <- 1:M
results <- rep(NA, nsim) # vector to store results
for(i in 1:nsim){
randomized_hats <- sample(hats,
size = M,
replace = FALSE)
results[i] <- sum(hats ==
randomized_hats) > 0
}
mean(results)
[1] 0.6285
set.seed(3) # set a seed for reproducibility
M <- 10 # number of people at the party
hats <- 1:M # numbered hats
nsim <- 10000 # number of simulations
results <- rep(NA, nsim) # vector to store the results
for(i in 1:nsim){
# hats are randomly assigned to each person
randomized_hats <- sample(hats, M, replace = F)
# did at least one person get their hat back?
results[i] <- sum(randomized_hats == hats) > 0
}
mean(results)
Work with a neighbor on the class activity (link below and on the course website):
https://sta279-f23.github.io/class_activities/ca_lecture_1.html