# Simulation 1

For this section we use loops to run little random scenarios -- like flipping a coin -- thousands of times to see what outcomes we get. In this way, the computer works as a sort of telescope, giving us insight about the space of outcomes but without requiring us to do any formal mathematics. Just run the simulation and see what it does! This is also known as "monte carlo simulation".

Class technique: can have students flip coins or dice or whatever, write sums on the board to try experiments by hand before doing them on the computer.

For the simulation code, the function call `random(1, 6)` returns a random number in between the two numbers (inclusive), so the result of random(1, 6) is like rolling a 6-sided die, and random(1, 2) is like flipping a coin.

The strategy will have an outer loop to run, say, 1000 trials. Inside the loop we have the code to run one trial. The function `series(1000)` returns a collection of the numbers 1, 2, 3... 1000. Using this, we can write a loop to iterate 1000 (or whatever number) times, like this

```for (i: series(1000)) {
...
}
```

To record what happens, we'll use the Histogram(min, max) class. Use histogram.add(val) to record one trial value, and print(histogram) to print its current state. The following code example demonstrates the use of all these functions:

### Coin Example 1

Flip a coin 100 times. How many times does heads come up? Try increasing the number of trials up from 100.

 histogram = new Histogram(1, 1); // min=1 max=1 for (i: series(100)) { // run 100 trials // --one trial-- coin = random(1, 2); // 1=heads, 2=tails if (coin == 1) { histogram.add(1); // record one trial on the histogram } } print(histogram);

### Coin Example 2

Say we flip 2 coins. How often will we get heads on both coins?

 histogram = new Histogram(1, 1); for (i: series(100)) { a = random(1, 2); b = random(1, 2); if (a == 1 && b == 1) { // two heads histogram.add(1); } } print(histogram);

### Coin Example 3

Say we flip 2 coins. How often will the two coins be the same?

 histogram = new Histogram(1, 1); for (i: series(100)) { a = random(1, 2); b = random(1, 2); if (a == b) { // coins are the same histogram.add(1); } } print(histogram);

## Coin Problems

Now the code is not included, so there are two problems: what its the that implements the experiment, and what numerically is the answer?

### Coin Problem 4

Say we flip 2 coins. How often do we get at least one head across the 2 coins?

 histogram = new Histogram(1, 1); for (i: series(100)) { a = random(1, 2); b = random(1, 2); // your code here } print(histogram);

### Coin Problem 5

Say we flip 3 coins, a b c. If a is tails, you automatically lose. If a is heads, then if at least one of b or c is tails, you win. How often do you win?

 histogram = new Histogram(1, 1); for (i: series(100)) { a = random(1, 2); b = random(1, 2); c = random(1, 2); // your code here } print(histogram);