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!
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