Skip to content

Instantly share code, notes, and snippets.

@alejandrohagan
Last active December 3, 2023 04:09
Show Gist options
  • Save alejandrohagan/2eccb97c3e3f872027df3a5a4d750159 to your computer and use it in GitHub Desktop.
Save alejandrohagan/2eccb97c3e3f872027df3a5a4d750159 to your computer and use it in GitHub Desktop.
Simulation of Riddler Gym
hi!
Thank you again for taking a look -- I'm trying to improve my simulation skills and curious where I might have the logic or intuition wrong with this riddler exercise
```{r}
library(tidyverse)
total_minutes <- 3*180
incremental_minutes <- total_minutes*.01
gym <- function(){
# create grid of gym participants -- everyone's ID correspondents to the # % of time they spend in the gym
grid <- tibble(
id=1:100
,availability=id/100
,total_gym_availability=total_minutes
,participant_minutes=total_minutes*availability
)
simulation <- grid %>%
rowwise() %>%
mutate(
avail_time=total_minutes-participant_minutes # available time window to participate
,avail_increments=avail_time/participant_minutes # the chunk they can participate
,start_time=sample(c(1:avail_increments),1)*incremental_minutes # random gym entry time within the window
,exit_time=min(start_time+participant_minutes,total_minutes) # when they leave the gym
,total_duration=exit_time-start_time # total time in gym
,check_ratio=total_duration/total_minutes # validate total time by proportion
) %>%
mutate(
timeframe=list(seq.int(from=1,to=total_minutes,by = 1)) # create timeframe minute by minute
) %>%
unnest(timeframe) %>%
ungroup() %>%
mutate(
gym_indicator= # indicator for when a participant was in the gym by timeframe
case_when(
start_time<=timeframe&timeframe<=exit_time~1
,TRUE~0
)
) %>%
select(id,availability,timeframe,gym_indicator)
# extract the time window of when 'I' went to the gym
window <- simulation %>%
filter(
id==50
,gym_indicator==1
) %>%
pull(timeframe)
# filter those gym goers that are in the gym at the same time as me
paricipants_in_gym <- simulation %>%
filter(
timeframe==min(window) & gym_indicator==1 #those participants that were there at the start of my time window and pull their ID numbers
,id!=50
) %>% pull(id)
# to validate the window range of the gym goe
# simulation %>%
# pivot_wider(
# names_from = timeframe
# ,values_from = gym_indicator
# ,names_repair = janitor::make_clean_names
# ) %>%
# relocate(id,availability,tidyselect::num_range("x",1:100)) %>%
# view()
# of everyone in the gym, sample at random who I meet first and check if there rank is over 50
results <- sample(paricipants_in_gym,1,replace = TRUE)>50
# returns a TRUE if over 50 and FALSE if under 50
return(results)
}
# replicate simulation 1000 times and take average of outcome
# runs slow -- probably many better ways to speed this up
out <- replicate(1000,gym())
mean(out)
```
@alejandrohagan
Copy link
Author

fixed error

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