How to resolve the algorithm 100 prisoners step by step in the R programming language

Published on 12 May 2024 09:40 PM
#R

How to resolve the algorithm 100 prisoners step by step in the R programming language

Table of Contents

Problem Statement

Show and compare the computed probabilities of success for the two strategies, here, on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm 100 prisoners step by step in the R programming language

Source code in the r programming language

t = 100000 #number of trials
success.r = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the random method
success.o = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the optimal method

#random method
for(i in 1:t){
  escape = rep(F,100)
  ticket = sample(1:100)
  for(j in 1:length(prisoner)){
    escape[j] = j %in% sample(ticket,50)
  }
  success.r[i] = sum(escape)
}

#optimal method
for(i in 1:t){
  escape = rep(F,100)
  ticket = sample(1:100)
  for(j in 1:100){
    boxes = 0
    current.box = j
    while(boxes<50 && !escape[j]){
      boxes=boxes+1
      escape[j] = ticket[current.box]==j
      current.box = ticket[current.box]
    }
  }
  success.o[i] = sum(escape)
}

cat("Random method resulted in a success rate of ",100*mean(success.r==100),
    "%.\nOptimal method resulted in a success rate of ",100*mean(success.o==100),"%.",sep="")


  

You may also check:How to resolve the algorithm Sum of a series step by step in the Octave programming language
You may also check:How to resolve the algorithm Anagrams step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Man or boy test step by step in the Ada programming language
You may also check:How to resolve the algorithm Object serialization step by step in the Racket programming language
You may also check:How to resolve the algorithm Knuth shuffle step by step in the uBasic/4tH programming language