0

I need to do a Monte Carlo simulation in R for this problem:

Three tourists arrive in a town that has five hotels. What is the probability that the three tourists each sign into a different hotel? And what is the probability they all sign in at the same hotel? The hotels have the same characteristics.

I'm lost with it, I tried with the code below, but didn't seem to work.

esperanza_Xn <- function(n,p,m) {
sim=0; q=1-p
for(i in 1:m){ 
   r=runif(n,1,p)
   e=2*r-1; X=0
   for(j in 1:n){
      X[j+1]=X[j]+e[j]
   }
   sim[i]=X[n+1]}
   a=paste("E(X_n) teórico=",n*(p-q))
   b=paste("E(X_n) Monte Carlo=",mean(sim))
   rbind(a,b)
}

EXAMPLE

esperanza_Xn(100,5,3)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
natiguvi
  • 1
  • 2
  • *Why* didn't it work? Do you have a stack trace? – Matt Sep 13 '15 at 01:53
  • 5
    Please don't re-post: http://stackoverflow.com/questions/32534667/monte-carlo-on-r – josliber Sep 13 '15 at 01:59
  • In addition, there are a few points that are not clear. 1) What are n, p, and m? 2) You say it "didn't seem to work" -- in what way did it not work? – josliber Sep 13 '15 at 02:02
  • 1
    We don't want to do your homework for you, but you do seem lost. So, some hints: make a vector of hotels (try: `LETTERS[1:5]`); simulate 1 iteration by taking a random sample of size 3 with replacement (look up the `sample(...)` function). Do this `n` times (look up the `replicate(...)` function). Then count the number of times all three letters in the sample are different (`length(unique(...))==3`). – jlhoward Sep 13 '15 at 02:22

1 Answers1

1

Getting rid of all the for loop:

sim.result <- replicate(n, sample(1:p, m, replace=TRUE))
hotel.count <- apply(sim.result, 2, function(x) length(unique(x)))

Then it is a matter of counting proportions:

# Probability of all different hotel assignment
mean(hotel.count == m)

# Probability of same hotel assignment
mean(hotel.count == 1)
Nishanth
  • 6,932
  • 5
  • 26
  • 38