Skip to content

Instantly share code, notes, and snippets.

@payne911
Created December 28, 2019 22:07
Show Gist options
  • Save payne911/96462fde9068f550255d82facbd56323 to your computer and use it in GitHub Desktop.
Save payne911/96462fde9068f550255d82facbd56323 to your computer and use it in GitHub Desktop.
R program for a small problem: probability to find 3 choices within 6 die-rolls (repetitions allowed, and counted)
roll <- function(rolls=6, die=1:6) {
dice <- sample(die, size = rolls, replace = TRUE)
}
verify <- function(a_roll=roll(), target=c(1,2,3)) {
if(length(a_roll) < length(target)) { # target requires more rolls
return (FALSE)
}
# cat("The roll being processed: ", a_roll, "\n")
for(choice in target) {
# cat("Currently looking at target: ", choice, " | Within roll: ", a_roll, "\n")
pre <- length(a_roll)
for(i in 1:pre) {
if(choice == a_roll[i]) { # looking for a match
a_roll <- a_roll[-i]
# cat("Found a match at index: ", i, "\n")
break
}
}
post <- length(a_roll)
# cat("pre-length: ", pre, " | post-length: ", post, "\n")
if(pre == post) { # we haven't found a match : ABORT
return (FALSE)
}
}
return (TRUE) # found a match for all choices : WIN
}
#################################################################################
results <- c() # future results
test <- function(trials=10000, test_target=c(1,3,1)) {
for(i in 1:trials) {
result <- verify(target=test_target)
results <- append(results, result)
}
print(table(results))
wins <- length(which(results==TRUE))
losses <- length(which(results==FALSE))
percentage <- 100*wins/length(results)
cat("Win percentage: ", percentage, "%\n")
}
@payne911
Copy link
Author

payne911 commented Dec 28, 2019

Results:

> test(trials=100000, test_target=c(1,2,3))
results
FALSE  TRUE 
75744 24256 
Win percentage:  24.256 %

> test(trials=100000, test_target=c(1,1,3))
results
FALSE  TRUE 
85016 14984 
Win percentage:  14.984 %

> test(trials=100000, test_target=c(1,1,1))
results
FALSE  TRUE 
93718  6282 
Win percentage:  6.282 %

Thus, it depends on the amount of duplicates in the desired target numbers.

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