How to resolve the algorithm Seven-sided dice from five-sided dice step by step in the R programming language

Published on 12 May 2024 09:40 PM
#R

How to resolve the algorithm Seven-sided dice from five-sided dice step by step in the R programming language

Table of Contents

Problem Statement

(Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple Random Distribution Checker.

Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Seven-sided dice from five-sided dice step by step in the R programming language

Source code in the r programming language

dice5 <- function(n=1) sample(5, n, replace=TRUE)


dice7.while <- function(n=1) 
{
   score <- numeric()
   while(length(score) < n)
   {
      total <- sum(c(5,1) * dice5(2)) - 3
      if(total < 24) score <- c(score, total %/% 3)
   } 
   score 
}
system.time(dice7.while(1e6)) # longer than 4 minutes


dice7.vec <- function(n=1, checkLength=TRUE) 
{
   morethan2n <- 3 * n + 10 + (n %% 2)       #need more than 2*n samples, because some are discarded
   twoDfive <- matrix(dice5(morethan2n), nrow=2)
   total <- colSums(c(5, 1) * twoDfive) - 3
   score <- ifelse(total < 24, total %/% 3, NA)
   score <- score[!is.na(score)]
   #If length is less than n (very unlikely), add some more samples
   if(checkLength) 
   {
      while(length(score) < n)
      {
         score <- c(score, dice7(n, FALSE)) 
      }
      score[1:n]
   } else score  
}
system.time(dice7.vec(1e6))   # ~1 sec


  

You may also check:How to resolve the algorithm Jensen's Device step by step in the EMal programming language
You may also check:How to resolve the algorithm Pythagorean quadruples step by step in the Sidef programming language
You may also check:How to resolve the algorithm Multi-dimensional array step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Boolean values step by step in the F# programming language
You may also check:How to resolve the algorithm Trabb Pardo–Knuth algorithm step by step in the OCaml programming language