averager

A class that can report the average of all numbers it has seen so far.

class Averager {
  int count;
  double sum;
  
  public void add(double x) {
    count += 1;
    sum += x;
  }
  
  public double mean() => sum / count;
}

Fibonacci numbers

A class that can generate a Fibonacci-like sequence starting with any two values.

class Fibonacci {
  int a, b;
  
  public Fibonacci(int a, int b) {
    this.a = a; this.b = b;
  }

  public Fibonacci() : this(1, 1) { }
  
  public int next() {
    int n = a;

    int c = a + b;
    a = b;
    b = c;
    
    return n;
  }
  
  public override string ToString() => $"{a}, {b}, ...";
}

complex numbers

A class representing a complex number.

class Complex {
  double real, imag;
  
  public Complex(double real, double imag) {
    this.real = real; this.imag = imag;
  }
    
  public static Complex add(Complex c, Complex d) =>
    new Complex(c.real + d.real, c.imag + d.imag);
    
  public override string ToString() =>
    $"${real} + ${imag} i";

  // Parse a complex number from a string such as "2.3+4.2i".
  public static bool tryParse(string s, out Complex c) {
    c = new Complex(0.0, 0.0);  // dummy value
    
    int i = s.IndexOf('+');
    if (i == -1 || !s.EndsWith("i")) return false;

    string first = s.Substring(0, i),
           second = s.Substring(i + 1, s.Length - i - 2);
    if (!double.TryParse(first, out double real) ||
        !double.TryParse(second, out double imag))
      return false;

    c = new Complex(real, imag);
    return true;
  }
}

recent averager

A class that can report the average of the last k numbers it has seen.

class RecentAverager {
  double[] a;
  int index;
  
  public RecentAverager(int k) {
    a = new double[k];
  }
  
  public void add(double d) {
    a[index] = d;
    index = (index + 1) % a.Length;
  }
  
  public double average() {
    double sum = 0;
    foreach (double d in a)
      sum += d;
    return sum / a.Length;
  }
}