Iteration with loops

Flipping a coin

Nasko
2022-06-08
flip <- function() {
  sample(c("T", "H"), 1)
}

output <- vector("double", 1000)

for(i in 1:1000) {
  flips <- 0
  nheads <- 0
  
  while(nheads < 3) {
    if(flip() == "H") {
      nheads <- nheads + 1
      
    } else {
      nheads <- 0
    }
    flips <- flips + 1
  }
  output[i] <- flips
}

ggplot() +
  geom_histogram(aes(output), bins=50)
table(output)
output
  3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19 
112  76  69  52  53  58  59  33  26  26  34  33  29  29  27  23  21 
 20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
 20  23  15  15  16  12   7   9  16   9   6   8   6   5   8   6   6 
 37  38  39  40  41  42  43  44  45  46  47  49  50  52  53  54  55 
  7   8   2   2   2   1   2   3   1   4   2   4   1   3   2   2   1 
 56  58  59  60  65 137 
  1   1   1   1   1   1