```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

To perform a calculation or simulation many times, we can use `replicate`. But this requires each trial to be independent and identical.

Sometimes, you want expression to depend on iteration. We'll use `for` *loops* in these cases.

Sometimes, we don't know at outset how many experiments to run. We'll use `while` *loops* in these cases


## For Loop

Suppose we want to add the first 100 integers.

```{r}

current_sum <- 0

for (i in 1:100 ) {
  current_sum <- current_sum + i 
  print( c(i,current_sum) )
}

```


## While Loop

How many times do we need to multiply 2 by itself for the product to exceed 1000?


```{r}

my_product <- 1
steps <- 0

while (my_product <= 1000 ){
  my_product <- my_product*2
  steps <- steps + 1
  print(c(steps, my_product))
}


```

## Seven Before Nine


Suppose we repeatedly roll a pair of dice. What is the probability of seeing a sum of 7 before a sum of 9?


How do we roll 2 dice and add results?


```{r}
# One experiment of rolling a pair of dice and summing
sum( sample(1:6, size = 2, replace = T) )
```

```{r}

sum_two <- 0

while (sum_two != 7 & sum_two != 9){
  sum_two <- sum( sample(1:6, size = 2, replace = T) )
}
```



Use replicate to replicate experiment 10,000

First create function for this experiment.

```{r}
seven_before_nine <- function(){
  sum_two <- 0

while (sum_two != 7 & sum_two != 9){
  sum_two <- sum( sample(1:6, size = 2, replace = T) )
}
  return(sum_two)
}
```

Now with replicate
```{r}
n_times <- 10^4
sum( replicate(n = n_times, seven_before_nine() == 7))/n_times
```

Is the true probability 60%?
