Here is the simulation of the problem of the drunken man and keys. Let me repeat the problem statement: A drunk man reaches his home and tries the door key from a bunch of 10 keys. If the first key doesn’t work, he returns the key to the bunch and randomly selects another key repeatedly until he opens the door. The question is: which precise trial has the highest probability of opening the door?
library(reshape)
library(ggplot2)
key <- 3
itr <- 100000
drunk <- replicate(itr, {
index <- 1
for(i in 1:100) {
sel <- sample(seq(1:10), 1, replace = TRUE, prob = rep(1/10,10))
if(sel == key){
index
break
}else{
index = index + 1
}
}
index
})
temp.melt <- melt(table(drunk))
ggplot(temp.melt, aes(x = drunk, y = value/itr)) +
theme_bw() +
geom_bar(stat = "identity", fill = "brown") +
xlim(0,20) +
labs(x= "Attempt #",
y= "Probability") +
theme(legend.position="none") +
theme(text = element_text(color = "black"),
panel.background = element_rect(fill = "antiquewhite1"),
plot.background = element_rect(fill = "antiquewhite1"),
panel.grid = element_blank())