PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 6, 2022

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

 October 06, 2022     probability, r, statistics     No comments   

Issue

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!


Solution

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


Answered By - gaut
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing