Imagine there is a lottery where you pick five numbers from an urn containing 100 numbers, 1 to 100. You win the draw if you select numbers in increasing or decreasing order. For example, [23, 34, 65, 80, 94] and [69, 54, 30, 18, 9] are winning sequences, but the string [12, 43, 32, 52, 94] is not.
What is the probability of winning the lottery?
Analytical solution
Suppose you pick five numbers at random from the basket of 100. The number of ways you can arrange those five is 5! = 120. Out of those, one sequence will be in the increasing order and one in the decreasing. So the chance of getting your winning lot is (1/120) + (1/120) = 2/120 = 1.67%
Monte Carlo
itr <- 100000
lot <- replicate(itr,{
sa <- sample(seq(1,100), 5, replace = FALSE)
all(diff(sa) < 0) | all(diff(sa) > 0)
})
sum(lot)*100/itr
You get an answer similar to the one before. Note that the function ‘all’ will return TRUE if all values match the criterion given a set of logical vectors. The function ‘diff’ calculates the difference between the elements ([element 2 – element 1], [element 3 – element 2] etc.) of a vector. For example,
diff(c(1,3,4,5)) # gives 2 1 1
all(diff(c(1,3,4,5)) > 0) # gives TRUE