Skip to content

Instantly share code, notes, and snippets.

@sschmutz
Created January 3, 2019 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sschmutz/e4f788db0839f2711b9be87e3f6f5c9e to your computer and use it in GitHub Desktop.
Save sschmutz/e4f788db0839f2711b9be87e3f6f5c9e to your computer and use it in GitHub Desktop.
538 Riddler Express - helping Santa
library(tidyverse)
# define amount of trials for the Monte Carlo Simulation
trial_n <- 1e5
order <- NULL
n_smaller <- NULL
# generate random order for each trial
for (trial in 1:trial_n) {
set.seed(181231 + trial)
order_trial <- c(1, sample(2:9, 8))
n_smaller_trial <- NULL
for (i in 1:9) {
smaller <- sum(order_trial[1:i] < order_trial[i])
n_smaller_trial <- c(n_smaller_trial, smaller)
}
order <- c(order, order_trial)
n_smaller <- c(n_smaller, n_smaller_trial)
}
# create tibble with simulations
simulations <-
crossing(trial = 1:trial_n,
position = 1:9) %>%
mutate(order = order,
n_smaller = n_smaller,
time_max = order,
time = time_max - n_smaller)
simulations_summary <-
simulations %>%
group_by(trial) %>%
summarize(time_total = sum(time))
# answer to Riddler Express question
mean_time_total <- mean(simulations_summary$time_total)
# plot mean time per position
position_order <- c(9:1)
simulations %>%
group_by(position) %>%
summarize(time_mean = mean(time)) %>%
mutate(position = factor(position, levels = position_order)) %>%
ggplot(aes(x = position, y = time_mean)) +
geom_col() +
scale_y_continuous(limits = c(0, 8)) +
labs(y = "mean time to find right reindeer [min]")
@sschmutz
Copy link
Author

sschmutz commented Jan 3, 2019

reindeer_order_solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment