Skip to content

Instantly share code, notes, and snippets.

@alejandrohagan
Last active September 13, 2024 03:06
Show Gist options
  • Save alejandrohagan/3487424aea73bc3fc03689b2c5b6fcf8 to your computer and use it in GitHub Desktop.
Save alejandrohagan/3487424aea73bc3fc03689b2c5b6fcf8 to your computer and use it in GitHub Desktop.
library(tidyverse)
#Flip 100 coins, labeled 1 through 100. Alice checks the coins in order (1, 2, 3, …) while Bob checks the odd-labeled coins, #then the even-labeled ones (so 1, 3, 5, …, 99, 2, 4, 6, …). Who is more likely to see two heads *first*?
library(tidyverse)
flip_coin <- function(){
flip_coin_tbl <- tibble(
coin=1:100
) |>
rowwise() |>
mutate(
face=sample(c(1,0),1)
) |>
ungroup()
method_1 <- flip_coin_tbl |>
filter(
face==1
) |>
mutate(
method1=duplicated(face)
) |>
filter(
method1==TRUE
) |>
pull(coin) |> min()
method_2 <- flip_coin_tbl |>
mutate(
even_indicator=coin%%2
) |>
arrange(
-even_indicator,coin
) |>
filter(
face==1
) |>
mutate(
method2=duplicated(face)
) |>
filter(
method2==TRUE
) |>
pull(coin) |> head(1)
out <- list()
out$method_1 <- method_1
out$method_2 <- method_2
out$flips <- flip_coin_tbl
if(method_1>method_2){
out$res <- tibble(
winner="method_2"
)
return(out)
}else if(method_1<method_2){
out$res <- tibble(
winner="method_1"
)
return(out)
} else {
out$res <- tibble(
winner="tie"
)
return(out)
}
}
out <- flip_coin()
out
res <- map(1:1000,\(x) flip_coin() |> pluck("res")) |>
purrr::list_rbind()
res |>
count(winner) |>
ggplot(aes(x=winner,y=n))+
geom_col()+
theme_classic()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment