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

Exercise 12.6
Using multiple interators


In this exercise we will see how to make good use of two interators of a single collection. Our starting point will be the type Interval, and the iterator which we have programmed for this type earlier in this teaching material.

For a given interval I, generate a list of all possible pairs (e,f) where both e and f come from I. As an example, the interval new Interval(1,2) should give rise to the list (1, 1), (1, 2), (2, 1), and (2, 2). For the purpose of generating the list of all such pairs, request two iterators from the interval, and traverse the interval appropriately in two nested while loops.

Like in the previous exercise, it is suggested that you use the operations in IEnumerator. Such a solution gives the best understanding of the use of multiple iterators. It is, however, also possible to solve this exercise by nested foreach loops.


Solution