Introduction to Computer Science

Start Lecture #11

Remark: Using the PC browse, http://java.sun.com/javase/6/docs/api

7.4.A: Matrix Multiply

public static void matrixMult (double [][] A,
                double [][] B, double [][] C) {
  // check that the dimensions are legal
  for (int i=0; i<A.length; i++)
    for (int j=0; j<A[0].length; j++) {
      A[i][j] = 0;
      for (int k=0; k<C.length; k++)
        A[i][j] += B[i][k]*C[k][j];
    }
}

Remark: Write the formula on the board. I do not assume you have memorized the formula. If it is needed on an exam, it will be supplied.

For multiplication the matrices must be rectangular. Indeed, if we are calculating A=B×C, then B must be an n×p matrix and C must be a p×m matrix (note the two ps). Finally, the result A must be an n×m matrix.

The code on the right does the multiplication, but it omits the dimensionality checking. Note that this checking will involve loops (to ensure that the arrays are not ragged).

An alternative would be to ask the user for the array bounds and trust that the arrays are of the size specified. Then the method definition would begin

public static void matrixMult (int n, int m, int p, double [][] A, double [][] B, double [][] C) {
  // A is an n by m matrix, B is n by p matrix, C is a p by m matrix
  

A full program for rectangular matrices is here.

Homework: 7.5.

Remark: Lab 2, Part 1 assigned. Due in 7 days. Changed to 9 days due to midterm.

7.5: Problem: Grading a Multiple-Choice Test

Read

7.6: Problem: Finding a Closest Pair

Read

7.6 (Alternate): Problem Choosing an Intermediate Point

import java.util.Scanner;
public class Intermediate {
  public static void main (String[] args) {
    final double [][] points = {  {0,0}, {3,4}, {1,9}, {-10,-10} };
    System.out.println("Input 4 doubles for start and end points");
    Scanner getInput = new Scanner(System.in);
    double [] start = {getInput.nextDouble(),getInput.nextDouble()};
    double [] end = {getInput.nextDouble(), getInput.nextDouble()};

    int minIndex = 0;
    double minDist = dist(start, points[0]) + dist(points[0], end);
    for (int i=1; i<points.length; i++)
      if (dist(start,points[i])+dist(points[i],end) < minDist) {
        minIndex = i;
        minDist = dist(start,points[i])+dist(points[i],end);
      }
    System.out.printf("Intermediate point number %d (%f,%f) %s%f\n",
              minIndex, points[minIndex][0], points[minIndex][1],
              " is the best.  The distance is ", minDist);
  }
  public static double dist(double [] p, double [] q) {
    return Math.sqrt((p[0]-q[0])*(p[0]-q[0])+
                     (p[1]-q[1])*(p[1]-q[1]));
  }
}

Assume you are given a set of (x,y) pairs that represent points on a map. For this problem we join the Flat Earth Society and assume the world is flat like the map.

Read in two (x,y) pairs S and E representing your starting and ending position and find which of the given points P minimizes the total trip, which consists of traveling from S to P and from P to E.

Note the following points about the solution on the right.

7.7: Problem: Sudoku

Not as interesting as the title suggests. The program in this section just checks if an alleged solution is correct.

7.8: Multidimensional (i.e., Higher Dimensional) Arrays

double x[][][] = {
               { {1,2,3,4}, {1,2,0,-1}, {0,0,-8,0} },
               { {1,2,3,4}, {1,2,0,-1}, {0,0,-8,0} }
             ];

There is nothing special about the two in two-dimensional arrays. We can have 3D arrays, 4D arrays, etc.

On the right we see a three 3D array x[2][3][4]. Note that both x[0] and x[1] are themselves 2D arrays.

7.8.1: Problem: Daily Temperature and Humidity

double[][][] data =
    new double[numDays][numHours][2];

double[][] temperature = new double[numDays][numHours]; double[][] humidity = new double[numDays][numHours];

The three dimensional array data on the upper right holds the temperature and humidity readings for each of 24 hours during a 10 day period.
data[d][h][0] gives the temperature on day d at hour h.
data[d][h][1] gives the humidity on day d at hour h.

However, I do not like this data structure since the temperature and humidity are really separate quantities so I believe the second data structure is better (the naming would be better).

double[][][] temperature =
    new double[numLatitudes][numLongitudes][numAltitudes];

On the right we see a legitimate 3D array that was used in a NASA computer program for weather prediction. The temperature is measured at each of 20 altitudes sitting over each latitude and longitude.

7.8.2: Problem: Guessing Birthdays

A cute guessing game. The Java is not especially interesting, but you might want to figure out how the game works.

Homework: 7.7

Remark: lab 2 part 2 assigned. Due in 7 days. Changed to 9 days due to midterm.

Remark: End of material on midterm.

Chapter 8: Objects and Classes

8.1: Introduction

Object-oriented programming (OOP) has become an important methodology for developing large programs. It helps to support encapsulation so that different programming teams can work on different aspects of the same large programming project.

Java has good support for OOP.

In Java, OOP is how gui programs are usually developed.

8.2: Defining Classes for Objects

An object is an entity containing both data (called fields in Java) and actions (called methods in Java). Two examples would be a circle in the plane and a stack.

For a circle, the data could be the radius and the (x,y) coordinates of the center. Actions might include, moving the center, changing the radius, or (in a graphical setting) changing the color in which the circle is drawn.

For a stack, the data could include the contents and the current top of stack pointer.

In Java, objects of the same type, e.g., many circles, are grouped together in a class.

Publis class Longstack {
  int top = 0;
  long[] theStack;
  void push(long elt) {
    theStack[top++] = elt;
  }
  long pop() {
    return theStack[--top];
  }
}

On the right is the beginnings of a class for stacks containing Java long's. The fields in the class are top and theStack; the methods are push() and pop().

Two obvious problems with this class are.

  1. The array theStack is declared but is not created (there is no new operation).
  2. It is an error to pop and empty stack, but this condition is not checked for.

Given a class, a new object is created by instantiating the class. Indeed, an object is often called an instance of its class.

Many classes supply a special method called a constructor that Java calls automatically whenever an object is instantiated. Although a constructor can in principle perform any action, normally its task is to initialize fields. For example the longStack constructor would create the array theStack.

8.3: Example: Defining Classes and Creating Objects

public class TestCircle1 {
  /** Main method */
  public static void main(String[] args) {
    // Create a circle with radius 5.0
    Circle1 myCircle = new Circle1(5.0);
    System.out.println("The area of the circle of radius "
      + myCircle.radius + " is " + myCircle.getArea());

    // Create a circle with radius 1
    Circle1 yourCircle = new Circle1();
    System.out.println("The area of the circle of radius "
      + yourCircle.radius + " is " + yourCircle.getArea());

    // Modify circle radius
    yourCircle.radius = 100;
    System.out.println("The area of the circle of radius "
      + yourCircle.radius + " is " + yourCircle.getArea());
  }
}

// Define the circle class with two constructors
class Circle1 {
  double radius;

  /** Construct a circle with radius 1 */
  Circle1() {
    radius = 1.0;
  }

  /** Construct a circle with a specified radius */
  Circle1(double newRadius) {
    radius = newRadius;
  }

  /** Return the area of this circle */
  double getArea() {
    return radius * radius * Math.PI;
  }
}

On the right is the example from the book. Note several points.

  1. There are two classes here. The top one is like many others we have seen in that it contains just the main() method. Since this class is public the file is named TestCircle1.java.
  2. The main method instantiates the second class Circle1 twice, thereby creating two Circle1 objects.
  3. In the first instantiation the radius is given; the second time it is not. Different constructors (called Circle1()) are called for the two cases (see below).
  4. The resulting objects myCircle and yourCircle can now be used in the main() method. For example both have their area computed and one has its radius changed.
  5. The Circle1 class is not public. It can only be used in this file (really this package). A single file can have only one (non-nested) public class; that class determines the name of the file.
  6. The class Circle1 has one field and three methods.
  7. The two methods, also named Circle, are constructors due to their name being the same as the name of the class.
  8. Since the constructors are overloaded, the signature is used to tell them apart. Both constructors serve the same purpose, they initialize the radius field.
  9. The third method getArea looks simple, we know the area of a circle is πr2, but ...
  10. It doesn't say static and ...
  11. Different circles have differing radii. How does getArea() know which radius to use?

The last two points above are closely related.