Week 4: Lecture/tutorial examples

vectors

A class representing a vector in Euclidean space.

class Vector {
  double[] a;
  
  public Vector(params double[] a) { this.a = a; }
  
  // length property
  public double length {
    get {
      double s = 0;
      foreach (double d in a)
        s += d * d;
      return Math.Sqrt(s);
    }
  }

  // indexer
  public double this[int index] {
    get {
      return a[index];
    }
    set {
      a[index] = value;
    }
  }
  
  // dot product using overloaded operator
  public static double operator * (Vector v, Vector w) {
    double s = 0;
    for (int i = 0 ; i < v.length ; ++i)
      s += v[i] * w[i];
    return s;
  }
  
}

dynamic array

class DynArray {
  int[] a = new int[1];
  int count;
  
  public int length {
    get => count;
  }
  
  public void add(int i) {
    if (count == a.Length) {
      int[] b = new int[count * 2];
      for (int j = 0 ; j < count ; ++j)
        b[j] = a[j];
      a = b;
    }
    
    a[count++] = i;
  }
  
  public int this[int index] {
    get => a[index];
    set => a[index] = value;
  }
}

stack, implemented using a linked list

class Node {
  public int i;
  public Node next;
  
  public Node(int i, Node next) {
    this.i = i; this.next = next;
  }
}

class LinkedStack {
  Node head;
  
  public bool isEmpty { get => (head == null); }

  public void push(int i) {
    head = new Node(i, head);
  }
  
  public int pop() {
    int i = head.i;
    head = head.next;
    return i;
  }
}