suspect_device
suspect_device

Reputation: 11

Monte Carlo for Pick 3 Lottery

This code is not working and I cant understand why.

n <- 10000
list <- numeric(n)

for(i in 1:n){
trial1 <- sample(0:9,3, replace = TRUE)
trial2 <- sample(0:9,3, replace = TRUE)
winner <- if(trial1 == trial2) 500 else -1
list[i] <-winner
}
mean(list)

Upvotes: 0

Views: 142

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

Do you want to return 500 only when the values are the same and are in order? Meaning 1, 2, 3 and 2, 3, 1 are different and return -1.

n <- 10000

return_result <- function() {
  trial1 <- sample(0:9,3, replace = TRUE)
  trial2 <- sample(0:9,3, replace = TRUE)
  if(all(trial1 == trial2)) 500 else -1
}

mean(replicate(n, return_result()))

If 1, 2, 3 and 2, 3, 1 are the same and should return 500 you can sort the result before comparing.

return_result <- function() {
  trial1 <- sample(0:9,3, replace = TRUE)
  trial2 <- sample(0:9,3, replace = TRUE)
  if(all(sort(trial1) == sort(trial2))) 500 else -1
}

mean(replicate(n, return_result()))

Upvotes: 1

Related Questions