Skip to content

Instantly share code, notes, and snippets.

@nstjhp
Created November 29, 2023 22:43
Show Gist options
  • Save nstjhp/dd7aa90587ecd9252e5cec18cdd46174 to your computer and use it in GitHub Desktop.
Save nstjhp/dd7aa90587ecd9252e5cec18cdd46174 to your computer and use it in GitHub Desktop.
library(RcppAlgos)
#' Calculate number of choices made by Shannon's bot
#' @description
#' Shannon's bot selects randomly answers to a multiple choice question the same
#' number of times as there is options to choose from.
#' It moves to the next question if at least 1 choice remains chosen after all
#' choices are made.
#' If not, i.e. nothing remains selected, the question is retried again, until
#' at least one choice remains.
#'
#' @references https://rdrr.io/cran/RcppAlgos/f/vignettes/CombPermConstraints.Rmd
#'
#' @param i An integer greater or equal to 2 (use 2L, 3L i.e. with L after to force integer)
#'
#' @return list of results
#'
#' @examples calc_choices(4L)
calc_choices = function(i) {
stopifnot("i must be an integer >= 2L e.g. calc_choices(2L)" = i > 1 & is.integer(i))
# weak means with 0s
compos_count = compositionsCount(0:i, repetition = TRUE, weak = TRUE)
# all compositions
all_comps = compositionsGeneral(0:i, repetition = TRUE, weak = TRUE)
assertthat::assert_that(compos_count == nrow(all_comps))
# As being chosen 3,5,7 etc times is the same as one time, modulo 2 everything
# Use integer 2L to keep everything ints
all_comps_mod2 = apply(all_comps, 2, function(.x) .x %% 2L)
# Find rows which are not all 0 (which are ignored as Shannon's bot
# restarts the question in this case)
all_comps_at_least_1_choice = apply(all_comps_mod2, 1, any)
# Find out how many rows are left (will be denominator)
eligible_comps = sum(all_comps_at_least_1_choice)
# Get column totals of choices
times_chosen = colSums(all_comps_mod2[all_comps_at_least_1_choice, , drop = FALSE])
# calc % times chosen
times_chosen_pc = 100*times_chosen/eligible_comps
return(list(compos_count = compos_count,
eligible_comps = eligible_comps,
times_chosen = times_chosen,
times_chosen_pc = times_chosen_pc,
unq_tc = unique(times_chosen),
unq_tcp = unique(times_chosen_pc)))
}
choice_results = Map(\(.i) calc_choices(.i), 2L:13L)
choice_res_pcs = unlist(lapply(choice_results, \(.z) .z$unq_tcp))
plot(2:13, choice_res_pcs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment