CS 46A - Lecture 16

Cover page image

Pre-class reading

Nested Loops

ch06/triangle1/Triangle.java

/**
   This class describes triangle objects that can be displayed
   as shapes like this:
   []
   [][]
   [][][]
*/
public class Triangle
{
   private int width;

   /**
      Constructs a triangle.
      @param aWidth the number of [] in the last row of the triangle.
   */
   public Triangle(int aWidth)
   {
      width = aWidth;
   }

   /**
      Computes a string representing the triangle.
      @return a string consisting of [] and newline characters
   */
   public String toString()
   {
      String r = "";
      for (int i = 1; i <= width; i++)
      {  
         // Make triangle row
         for (int j = 1; j <= i; j++)
            r = r + "[]";
         r = r + "\n";
      }
      return r;
   }
}

File TriangleRunner.java

/**
   This program prints two triangles.
*/
public class TriangleRunner
{
   public static void main(String[] args)
   {
      Triangle small = new Triangle(3);
      System.out.println(small.toString());

      Triangle large = new Triangle(15);
      System.out.println(large.toString());
   }
}

Program Run:

Nested Loop Examples

Nested Loop Examples

Nested Loop Examples

Nested Loop Examples, continued

Lecture 16 Clicker Question 1

What does this loop print?

for (int i = 1; i <= 10; i++)
{
   for (int j = 1; j <= 10; j++)
     if (i + j <= 10) Print " " else Print "*"
   System.out.println();
}
  1. A triangle like ◢
  2. A triangle line ◤
  3. A triangle like ▲
  4. Something else

Lecture 16 Clicker Question 2

What is the value of n after the following nested loops?
int n = 0;
for (int i = 1; i <= 5; i++)
   for (int j = 0; j < i; j++)
      n = n + j;

  1. 20
  2. 35
  3. 75
  4. Something else

Random Numbers and Simulations

ch06/random1/Die.java

import java.util.Random;

/**
   This class models a die that, when cast, lands on a random
   face.
*/
public class Die
{
   private Random generator;
   private int sides;

   /**
      Constructs a die with a given number of sides.
      @param s the number of sides, e.g. 6 for a normal die
   */
   public Die(int s)
   {
      sides = s;
      generator = new Random();
   }

   /**
      Simulates a throw of the die
      @return the face of the die 
   */
   public int cast()
   {
      return 1 + generator.nextInt(sides);
   }
}

ch06/random1/DieSimulator.java

/**
   This program simulates casting a die ten times.
*/
public class DieSimulator
{
   public static void main(String[] args)
   {
      Die d = new Die(6);
      final int TRIES = 10;
      for (int i = 1; i <= TRIES; i++)
      {  
         int n = d.cast();
         System.out.print(n + " ");
      }
      System.out.println();
   }
}

Program Run:

Lecture 16 Clicker Question 3

Which of these can be used to generate a random  letter  A, B, C, or D?

  1. "ABCD".substring(generator.nextInt(4), generator.nextInt(4) + 1)
  2. "A" + generator.nextInt(4)
  3. 'A' + (int)(4 * generator.nextDouble())
  4. None of the above

Buffon Needle Experiment

Figure 3 - The Buffon Needle Experiment

Needle Position

Figure 4 - When Does the Needle Fall on a Line?

Needle Position

ch06/random2/Needle.java

import java.util.Random;

/**
   This class simulates a needle in the Buffon needle experiment.
*/
public class Needle
{
   private Random generator;
   private int hits;
   private int tries;

   /**
      Constructs a needle.
   */
   public Needle()
   {
      hits = 0;
      tries = 0;
      generator = new Random();
   }

   /**
      Drops the needle on the grid of lines and 
      remembers whether the needle hit a line.
   */
   public void drop()
   {
      double ylow = 2 * generator.nextDouble();
      double angle = 180 * generator.nextDouble();
      
      // Computes high point of needle
      
      double yhigh = ylow + Math.sin(Math.toRadians(angle));
      if (yhigh >= 2) hits++;    
      tries++;
   }

   /**
      Gets the number of times the needle hit a line.
      @return the hit count
   */
   public int getHits()
   {
      return hits;
   }

   /**
      Gets the total number of times the needle was dropped.
      @return the try count
   */
   public int getTries()
   {
      return tries;
   }       
}

ch06/random2/NeedleSimulator.java

/**
   This program simulates the Buffon needle experiment 
   and prints the resulting approximations of pi.
*/
public class NeedleSimulator
{
   public static void main(String[] args)
   {
      Needle n = new Needle();
      final int TRIES1 = 10000;
      final int TRIES2 = 1000000;

      for (int i = 1; i <= TRIES1; i++)
         n.drop();
      System.out.printf("Tries = %d, Tries / Hits = %8.5f\n",
            TRIES1, (double) n.getTries() / n.getHits());

      for (int i = TRIES1 + 1; i <= TRIES2; i++)
         n.drop();
      System.out.printf("Tries = %d, Tries / Hits = %8.5f\n",
            TRIES2, (double) n.getTries() / n.getHits());
   }
}

Program Run:

Lecture 16 Clicker Question 4

Why is the NeedleSimulator program not an efficient method for computing π?

  1. You can never compute a value accurately by using random numbers
  2. The program must generate two random numbers per iteration, which is slow.
  3. The program repeatedly calls Math.sin(angle). You could compute π much more easily with that method.
  4. The program repeatedly calls Math.toRadians(angle). You could compute π much more easily with that method.