Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Using multiple interators


Here is the program that generates the list of all pairs of numbers from an interval:

using System;
using System.Collections;
using System.Collections.Generic;

public class app {

  public static void Main(){

    Interval iv1 = new Interval(1,2);

    IEnumerator e1 = iv1.GetEnumerator(),
                e2 = iv1.GetEnumerator();

    List<Pair<int,int>> pairs = new List<Pair<int,int>>();

    while (e1.MoveNext()){
      while (e2.MoveNext())
         pairs.Add(new Pair<int,int>((int)(e1.Current), (int)(e2.Current)));
      e2.Reset();
    }

    foreach(Pair<int,int> p in pairs)
      Console.WriteLine("({0}, {1})", p.First, p.Second);
  }
}

The program makes use of generic class Pair<T,S> which can be programmed in the following way:

using System;

public class Pair<T,S>{
  private T first;
  private S second;

  public Pair(T first, S second){
    this.first = first; this.second = second;
  }

  public T First{
     get {return first;}
  }

  public S Second{
     get {return second;}
  }
  
}