R/montyhall.R

# Generated by LaTeX DogWagger Version 4.0.5 from file <NCTLL_904.tex>
# Date: [2020-9-17 13:16:5] 
# Do NOT edit this file. Edit the LaTeX source!!

# - <Section 3> - 
#' A Monte Carlo simulation of the Monty Hall problem
#' 
#' @param runs specifies the number of parallel simulations, default=100. 
#' @keywords corona coronavirus Monty Hall Monte Carlo simulation 
#' @export 
#' @importFrom stats runif
#' @examples
#' corona_monty ( runs=10000 ) 

corona_monty <- function ( runs=100 ) 
{ car <- 1 + as.integer(runif(runs, min=0, max=3)); 
  goata <- 1 + (car %% 3); 
  goatb <- 1 + ( (car+1) %% 3 ); 
  mydoor <- as.integer(runif(runs, min=1, max=4)); 
  adoor <- as.integer(runif(runs, min=0, max=2)); # one of 2 doors 1=open goata, 0=open goatb
      # Use 0 to signal an open door: 
  goatb <- goatb * !(mydoor == goata); 
  goata <- goata * !(mydoor == goatb); 
  neither <- goata & goatb;  # unselected i.e. mydoor=car, 
  goata <- goata * ! ( neither & adoor ); # for all not-selected, open goata if adoor is true
  goatb <- goatb * ! ( neither & (! adoor) ); # for all not-selected, open goatb if adoor is NOT true
      # count wins in unswapped state, noting you either win or lose, and wins+losses=runs
  wins <- sum( 1 * (mydoor == car) ); 
      # offer the choice to swap: 
  swap <- readline(prompt = 'Do you want to swap? (y/N)  '); 
  swap <- toupper( substr(swap,1,1));
if(swap == 'Y')
  { wins <- runs - wins; 
    print('Swapped your door choice!'); 
  }; 
  print( paste('There were', wins, 'wins in', runs, 'simulations') ); 
} 
# -END OF FILE- 
jvanschalkwyk/corona documentation built on Oct. 3, 2020, 11:01 a.m.