0

Working on some Monte Calo simulations:

A waiting line consists of 40 men and 10 women arranged in random order. Need to estimate the probability that no two women in line are adjacent to one another.

nrep = 100000
count = 0 
for (i in 1:nrep) {

Now for the sample is there a way where I can write "40 M" and the program read that as 40 different objects?

and for the question can I ask if there are women next to each other out of the 10 total?

  • Hi user12110851. Welcome to StackOverflow! Please read the info about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and how to give a [minimale reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). That way you can help others to help you! – dario Feb 23 '20 at 15:22

2 Answers2

1

How about this:

library(zoo)
library(tidyverse)

isWoman <- c(rep(FALSE, 40), rep(TRUE, 10)) # the vector to sample from

twoAdjacent <- function(x) rollsum(x, 2) >= 2 # a helper function that calculates for a logical vector whether two TRUEs are next to each other

# and now the simulation (see explanation below)
replicate(
    10000
    , isWoman %>% sample() %>% twoAdjacent() %>% any() %>% `!`) %>%
    mean()

So, important to understand is the %>% (pipe-operator): read it as "then". Read the 3rd line first:

  • we take the vector isWoman
  • randomly sort it (sample())
  • see check where there are two adjacent TRUEs (twoAdjacent())
  • check if this appears anywhere
  • and apply a logical NOT (!)

We replicate this 10000 times, which gives us a logical vector of length 10000. Eventually we pass this (logical) vector to the mean() function where every TRUE is interpreted as a 1 and every FALSE as a 0. Hence, the result is the probability you are looking for.

Georgery
  • 7,643
  • 1
  • 19
  • 52
0

Maybe you can try the base R code below, where M is for men, W is for women

M <- rep(0,40)
W <- rep(1,10)
nrep <- 1e5

# define your custom function that counts the event of no adjacent women
fcnt <- function(v) +all(diff(which(v==1))>1)
# use `mean` to calcuaute the frequency (or probability) of event
p <-mean(replicate(nrep,fcnt(sample(c(M,W)))))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81