Week 3: Notes

Here are the two classes we saw in the lecture. They demonstrate the C# features we discussed including private and public fields, instance methods, static methods, constructors, and constructor chaining.

Point

class Point {
  public int x, y;
  
  public Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
  
  // Construct a Point from a string such as "34 -12".
  public Point(string s) {
    string[] a = s.Split();
    x = int.Parse(a[0]);
    y = int.Parse(a[1]);
  }
  
  // Return the Manhattan distance from this point to p.
  public int dist(Point p) {
    return Abs(this.x - p.x) + Abs(this.y - p.y);
  }
  
  // Return the Manhattan distance from p to q.
  static int dist(Point p, Point q) {
    return Abs(p.x - q.x) + Abs(p.y - q.y);
  }
  
  // Construct a Point from a string such as "34 -12".
  static Point parse(string s) {
    string[] a = s.Split();
    return new Point(int.Parse(a[0]), int.Parse(a[1]));
  }
}

Stack

// A fixed-size stack.
class Stack {
  int[] a;
  int count = 0;
  
  public Stack(int max) {
    a = new int[max];
  }
  
  public Stack() : this(100) {
  }
  
  public void push(int i) {
    a[count] = i;
    ++count;
  }
  
  // push i, n times
  public void push(int i, int n) {
    for (int j = 0 ; j < n ; ++j)
      push(i);
  }
  
  public int pop() {
    --count;
    return a[count];
  }
  
  public bool isEmpty() {
    return count == 0;
  }
}

Time

In the lab we began to solve this week's exercise #1, which involves writing a Time class. Here is as much of the class as we have written so far:

class Time {
  int seconds;  // seconds since midnight, 0 .. (24 * 3600 - 1)
  
  public Time(int hour, int min, int sec) {
    seconds = 3600 * hour + 60 * min + sec;
  }
  
  public Time(int hour, int min) : this(hour, min, 0) {
  }
  
  // private constructor
  Time(int seconds) {
    this.seconds = seconds;
  }
  
  public Time add(int delta) {
    int t = (seconds + delta) % 24 * 3600;
    return new Time(t);
  }
}