简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM