What is the probability that A and B sit next to each other?

Viewed 90

We have a group of 20 people. We want to arrange them in a row in such way that A and B sit next to each other. I have to find the probability of that event in R language.

My solution is:

f1 <- function() {
  x <- sample(c(1:20), 20, replace = F)
  
  for (i in c(1:19)) {
    
    if (x[i] == 1 && x[i+1] == 2 
        || (x[i] == 2 && x[i + 1] == 1)) {
     TRUE
    }
  }
  
  F
  
}

prob_p <- function(Nrep) {
  rs <- replicate(Nrep, f1())
  sum(rs) / length(rs)
}

prob_p(100000)

I think I have some mistake in my solution, because when I run this code(I use RStudio), the result of the probability is 0.

Can you help me with figuring out what the problem is. Any help or advice would be appreciated. Thank you in advance!

3 Answers

You can avoid a lot of indexing, looping, incrementing, accumulating, etc. if you use R's native facilities. Try this to see if person 1 and person 2 occurs next to each other or not.

 set.seed(345452L)
 run1trial <- function ()
   {# local vars used here to make the logic easy to see
    samp <- sample(1:20,20)
    a <- abs(which(samp==1)-which(samp==2)) 
    if ((a==1)) { return(1)}
    else {return(0)}
   }
 
 trials <- 100000
 out <- replicate(trials,run1trial())
 sum(out)/trials    

 # > sum(out)/trials    
 # [1] 0.09935

With R you rarely need to define your own loops as the various structures--vectors of length(n) in this case, but the same occurs with dataframes, lists, etc.--contain all the information necessary to do the indexing, incrementing, summing, etc. under the hood.

Note that it is possible to have 2 equivalent permutations. Given 10^18 permutations, this isn't likely much of a problem, however there is a package which can assure nonreplicated permutations: https://cran.r-project.org/web/packages/RcppAlgos/vignettes/GeneralCombinatorics.html

Just return your result from f1:

f1 <- function() {
  x <- sample(c(1:20), 20, replace = F)
  result <- FALSE
  for (i in c(1:19)) {
    
    if (x[i] == 1 && x[i+1] == 2 
        || (x[i] == 2 && x[i + 1] == 1)) {
      result <- TRUE
    } 
  }
  
  result # identical to return(result)
}

prob_p <- function(Nrep) {
  rs <- replicate(Nrep, f1())
  sum(rs) / length(rs)
}
prob_p(100000)
[1] 0.0988

If you want to run monte carlo simulations, you can try mean + replicate + grepl + sample like below

prob_p <- function(n) {
  v <- head(LETTERS,20)
  mean(replicate(n, grepl("AB|BA", paste0(sample(v), collapse = ""))))
}

such that

> prob_p(100000L)
[1] 0.10003

Mathematically, I guess the solution should be

> factorial(2)*factorial(19)/factorial(20)
[1] 0.1
Related