next up previous
Next: Multiple recursion Up: Unit 11 Previous: Example: palindrome string

Example: symmetric sequence of integers

A sequence of integers that are all positive except for a single 0 in the central position is said to be symmetric if the sequence coincides with the same sequence when we invert it. For example, the sequence 5 8 3 0 3 8 5 is symmetric, while the sequence 5 8 3 0 8 5 3 is not so.

Suppose we have a text file (which we access through a BufferedReader) containing a sequence of integers, one per line, all positive, except for a 0 in the central position, and we want to check whether it is symmetric. One possibility is to store the whole sequence in an array, and do the check by directly accessing the elements of the array. This can be done either by using a loop, or through recursion, similarly as to what we have done for palindrome strings. However, using recursion, we can do the check also without using (explicitly) an additional data structure.

Let us first provide an inductive characterization of a sequence of integers with a 0 in the middle that is symmetric, similar to the one given for palindrome strings:

Using such a characterization, we can provide a recursive implementation of the check whether the file contains a sequence of positive integers with a 0 in the middle that is symmetric (if the file contains additional lines at the end these are ignored).

public static boolean symmetric(BufferedReader br) throws IOException {
  int n = Integer.parseInt(br.readLine());    // read the first integer
  if (n == 0)
    return true;         // we are in the middle of the sequence
  else {
    // read the sequence in the middle and check whether it is symmetric
    boolean sim = symmetric(br);
    int m = Integer.parseInt(br.readLine());  // read the last integer
    return (n == m) && sim;
  }
}


next up previous
Next: Multiple recursion Up: Unit 11 Previous: Example: palindrome string