Week 5: Lecture/tutorial examples

points

struct Point {
  public double x, y;
  
  public Point(double x, double y) { this.x = x; this.y = y; }
  
  public static double distance(Point p, Point q) =>
    Sqrt((p.x - q.x) * 2 + (p.y - q.y) * 2);
}

stacks

interface Collection {
  bool isEmpty { get; }
}

interface Stack : Collection {
  void push(int i);
  int pop();
}

interface Queue : Collection {
  void enqueue(int i);
  int dequeue();
}

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

class LinkedStack : Stack {
  Node head;
  
  public virtual void push(int i) {
    head = new Node(i, head);
  }
  
  public virtual int pop() {
    int i = head.i;
    head = head.next;
    return i;
  }
  
  public bool isEmpty { get => (head == null); }
}

class AvgStack : LinkedStack {
  int count;
  int sum;
  
  public override void push(int i) {
    base.push(i);
    count += 1;
    sum += i;
  }
  
  public override int pop() {
    int i = base.pop();
    count -= 1;
    sum -= i;
    return i;
  }
  
  public double average {
    get => (double) sum / count;
  }
}

streams

interface IntStream {
  int? next();  // returns null at end of stream
}

// The sequence of Fibonacci numbers: 1, 1, 2, 3, 5, 8, ...
class FibStream : IntStream {
  int a = 1, b = 1;
  
  public int? next() {
    int n = a;
    int c = a + b;
    a = b;
    b = c;
    return n;
  }
}

// A sequence of integers from 'from' to 'to', inclusive.
class IntRange : IntStream {
  int current, to;
  
  public IntRange(int from, int to) {
    current = from; this.to = to;
  }
  
  public int? next() {
    if (current <= to)
      return current++;
    else return null;
  }
}

// A SquareStream squares all values in a source stream.
class SquareStream : IntStream {
  IntStream source;
  
  public SquareStream(IntStream source) { this.source = source; }
  
  public int? next() {
    if (source.next() is int i)
      return i * i;
    else return null;
  }
}

static class Top {
  // Return the sum of all values in a stream.
  static int sum(IntStream stream) {
    int s = 0;
    while (stream.next() is int i)
      s += i;
    return s;
  }

  // Write the sum of the squares of integers from 1 to 10.
  static void summer() {
    WriteLine(sum(new SquareStream(new IntRange(1, 10))));
  } 
  
}