Five players are in a tournament, where each player plays one game with every other. If a player must win every game, what is the probability that one player wins all her matches? The analytical solution is available in the reference below; let’s estimate it numerically.
While the problem is straightforward, I found the coding a bit tricky. Let me explain my logic here step-by-step.
Getting the list of all the matches is perhaps the easiest. Use the function, ‘combinations’ (make sure you installed the library, ‘gtools’).
library(gtools)
play <- combinations(5,2)
play
[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 1 5
[5,] 2 3
[6,] 2 4
[7,] 2 5
[8,] 3 4
[9,] 3 5
[10,] 4 5
Next, take each of these ten combinations and pick a winner with a 50% probability (using the ‘sample’ function).
for (x in 1:10) {
play1 <- c(play[x,])
score[x] <- sample(play1, 1, replace = TRUE, prob = c(1/2,1/2))
}
One such realisation is below:
1 1 1 5 2 2 2 4 5 5
The rest is okay; check a number that repeats four times (four wins). The ‘table’ function can give counts for each number.
table(score)
score
1 2 4 5
3 3 1 3
The output means (read top to bottom): 1 repeated 3 times, 2 repeated 3 times, 4 repeated 1 time and 5 repeated 3 times.
But we only need the frequency (the ‘times’) four times (if any). For example, in the previous case, if we want to know which number is repeated one time, the following code gives the output.
table(score)[table(score) == 1]
4
1
length(table(score)[table(score) == 1])
1
The rest is smooth: make a counter for four repetitions, repeat the process a million times and find the average.
itr <- 1000000
win <- replicate(itr,{
score <- c(1:10)
for (x in 1:10) {
play1 <- c(play[x,])
score[x] <- sample(play1, 1, replace = TRUE, prob = c(1/2,1/2))
}
if(length(table(score)[table(score) == 4]) == 0 ){
counter <- 0
}else{
counter <- 1
}
})
mean(win)
You get 0.312. The analytical solution is 5/16. We will discuss the derivation in the next post.
A probability technique worth knowing: MindYourDecisions