jeudi 16 mai 2019

For loop including "if" and "while" running for hours

I have a for loop including “if” and “while” clauses written for a question. It is intended to do 1000 simulations with some conditions. I think it is not a very complicated loop, but it has been running for almost 16 hours without showing a result or prompting an error/warning (and the little red stop sign has been shown all this time), and I can feel that my laptop has been slowed down since I started running the loop.

So I wonder if this is something that could actually happen, or if there’s anything wrong with my code or my laptop. Any help is greatly appreciated!!

Please see below for the code:

result.Vec <- NULL
for (trials in 1:1000) {
  sum <- 0
  sum2 <- 0
  n <- 0
  tmp1 <- sample(x=c(1, 2, 3, 4, 5, 6), size=1, replace=T, prob=c(1/6, 1/6, 1/6, 1/6, 1/6, 1/6)) 
  tmp2 <- sample(x=c(1, 2, 3, 4, 5, 6), size=1, replace=T, prob=c(1/6, 1/6, 1/6, 1/6, 1/6, 1/6)) 
  sum <- tmp1 + tmp2
  if (sum == 7 || sum == 11) {
    n <- 1
   } else if (sum == 2 || sum == 3 || sum == 12) {
    n <- 0
   } else {
     while (sum2 != sum || sum2 != 7) {
       tmp1 <- sample(x=c(1, 2, 3, 4, 5, 6), size=1, replace=T, prob=c(1/6, 1/6, 1/6, 1/6, 1/6, 1/6)) 
       tmp2 <- sample(x=c(1, 2, 3, 4, 5, 6), size=1, replace=T, prob=c(1/6, 1/6, 1/6, 1/6, 1/6, 1/6)) 
       sum2 <- tmp1 + tmp2
       if (sum2 == sum) {
         n <- 1
       } else if (sum2 == 7) {
         n <- 0
       }
     }
   }
  result.Vec <- c(result.Vec, n)
}

Please see below for the question that my loop is for as a reference (not seeking a solution to this problem): The dice game craps is played as follows. The player throws two dice, and if the sum is seven or eleven, then she wins. If the sum is two, three, or twelve, then she loses. If the sum is anything else, then she continues throwing until she either throws that number again (in which case she wins) or she throws a seven (in which case she loses). Calculate the probability that the player wins based on 1000 simulations.

Aucun commentaire:

Enregistrer un commentaire