RoiMinuit
RoiMinuit

Reputation: 414

Monte Carlo Simulation for Pattern

I am writing a Monte Carlo simulation to check how many times y was not immediately next to another y. I conjured up a vector of 40 x's and 10 y's placed at random position in the vector. My goal is to calculate the probabilities of not having any adjacent y's in the vector. Here is what I tried:

nrep = 100000
count = 0
for (i in 1:nrep) {
  x = sample(c(rep('x', 40), c(rep('y', 10))))
  if (x[i]!=x[i+1] && x[i+1]!=x[i+2]) count = count + 1
}
print(count/nrep)

The result is a very small number, which doesn't seem to make sense to me.

Upvotes: 0

Views: 107

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

The if part is not correct. We can use head/tail to check for consecutive elements and see if there are any two consecutive 'y's in one iteration.

nrep = 100000
count = 0
set.seed(2020)

for (i in 1:nrep) {
  x = sample(rep(c('x', 'y'), c(40, 10)))
  if(any(head(x, -1) == 'y' & tail(x, -1) == 'y')) count = count + 1
}

count/nrep
#[1] 0.891

Upvotes: 1

Related Questions