Skip to content

Instantly share code, notes, and snippets.

@vftools
Created December 7, 2017 22:53
Show Gist options
  • Save vftools/7b79a05a0e5dd4e605d79b3c7fce8974 to your computer and use it in GitHub Desktop.
Save vftools/7b79a05a0e5dd4e605d79b3c7fce8974 to your computer and use it in GitHub Desktop.
Murder game: what are the chances of a full cycle?
## n people draw lots (of each other). What are the chances of a full cycle?
## Draw lots
draw_lots <- function(n, allow_self = F) {
draw <- sample(n, n)
while(allow_self == F & any(draw == 1:n)) {
draw <- sample(n, n)
}
return(draw)
}
## 1 begins killing and only stops when they get their own card again.
## By that point, what is their murder count?
## Function will return TRUE if the cycle has length n, FALSE otherwise.
full_cycle <- function(draw) {
murderer <- 1
victim <- 0
murder_count <- 0
while(victim != 1) {
victim <- draw[murderer]
murderer <- victim
murder_count <- murder_count + 1
}
return(murder_count == length(draw))
}
## Run Monte Carlo Simulation
run_mc <- function(n, iterations = 10000, allow_self = F) {
cycles <- sapply(rep(n, iterations), function(x){full_cycle(draw_lots(x, allow_self = allow_self))})
chance <- sum(cycles) / length(cycles)
return(chance)
}
run_mc(18, allow_self = F)
## Probability functions
full_cycle_prob1 = function(n){
if(n<3){return(1)}
x = 0
for(i in 0:(n-2)){
x = x + (-1)^i * (n-i-1) * factorial(n-2)/factorial(i)
}
return(factorial(n-1)/((n-1)*x))
}
full_cycle_prob2 <- function(n) {
factorial(n-1)/round(factorial(n)/exp(1),0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment