Lecture 12, CS 302-6, September 30

 

  1. Review
    1. Loops: For, while, do
    2. Sentinel values
    3. Things you can do with loops
  2. Nested Loops
    1. Just a loop inside a loop
    2. Example –iterating students in class

                                                               i.      Columns, rows of chairs

    1. Printing a table of values with .print and .println
    2. Example – MultTable.java
    3. We can also use nested loops to run multiple things through a loop
    4. Example – WordsAndLetters.java
    5. We covered factoring quickly at the end of last class – let’s look at it again in the context of determining prime numbers
    6. Example – Primes.java
  1. Simulations
    1. This is another application of loops.
    2. We can perform the same random task many times to approximate solutions – computers are good at this.
    3. Simple examples: coin flips, dice rolls, etc

                                                               i.      Imagine flipping 1,000,000 coins.  Chances are about half of them will be heads.

    1. One example: estimating pi via the Monta Carlo method

                                                               i.      Unit circle

                                                             ii.      Area – pi*r^2

                                                            iii.      X, y random between 0 and 1

                                                           iv.      X^2+y^2<=1

                                                             v.      Probability of landing in circle: pi/4

                                                           vi.      Example – MonteCarlo.java

1.      (we didn’t actually code this in class)

    1. Monty Hall problem

                                                               i.      Imagine game show, three doors.  2 have goats behind them, one has a new car.  Pick a door.  Host opens another to show goat.  Should you switch to the other unopened door?

                                                             ii.      Best strategy: Switch.  Why?  Higher probability

                                                            iii.      Don’t believe me?  See http://en.wikipedia.org/wiki/Monty_Hall_problem

                                                           iv.      We’ll code this up next class

  1. HW
    1. Read 6.1-6.2