Computer Science 301 - 2006

Programming Language Translation


Practical for Week 19, beginning 28 August 2006 - Solutions

The submissions received were very varied, but on the whole of rather reasonable quality. There was some innovative work handed in, but there was evidence that people had missed several important points. You can find complete source versions of the program solutions in the solution kit PRAC19A.ZIP on the server. This file also contains C# versions of the solutions for people who might be interested.

Some general comments:

(a) You should always put your names and a brief description of the program into the source code.

(b) Several submissions had almost no commentary at all, and this is just unacceptable. In particular, supply commentary at the start of each method as to what it sets out to do, and on the significance of the parameters/arguments.

(c) Several submissions in this prac suggested that you have all learned to comment out code stolen from elsewhere, rather than deleting it properly when it has no bearing on the task in hand. That is really very sloppy, and makes for lots of confusion on the part of people trying to work out what you are really trying to do.

(d) The pracs in this course are deliberately set to extend you, in the hope that you will learn a lot from each one. Their completion requires that you apply yourself steadily throughout the week, and not just on Thursday afternoon and the following Thursday morning!

(e) A large number of submissions were received that had not made use of the IO, InFile and OutFile classes as you had been told to do. These library classes are designed to make text based I/O as simple as possible without having to deal with buffered readers, exceptions, string tokenizers and all that stuff that you were probably subjected to in CSC 102, but without realising that the best thing to do with bizarre code is to hide its details in a well-designed library. Have a look at the solutions below, where hopefully you will see that the I/O aspects have been made very simple indeed.


Tasks 2 to 7 - The Sieve of Eratosthenes

The first tasks were fairly straightforward, though several groups obviously had not bothered to see whether the extended sieve programs would execute properly. The Pascal compiler only uses 16-bit INTEGER arithmetic (-32768 .. 32767) but it appears to allow large sieve sizes, as arrays can also be indexed by so-called long variables. Since it regards an integer as a signed 16-bit number, an extra limitation is imposed - an array indexed by an integer cannot have an upper subscript greater than 32767. But it's even worse than that! Consider the code:

            K := I (* now cross out multiples of I *);
            REPEAT
              Uncrossed[K] := FALSE; K := K + I
            UNTIL (K > N);

When I becomes large enough, K+I really should become larger than 32767, but the overflow means that it appears to go negative (think back to your CSC 201 course). This happens for the first time after detecting the prime number 16411, so that the maximum effective sieve with the code above is really only 16410.

We can extend the range of the algorithm by a trick which I did not expect you to discover, but which may be worth pointing out. Replace the above code by

            K := I (* now cross out multiples of I *);
            REPEAT
              Uncrossed[K] := FALSE; K := K + I
            UNTIL (K > N) OR (K < I)

which looks ridiculous, but when K gets too large and then overflows, since it appears to become negative it will then also appear to be less than I.

All rather subtle - up till now you probably have not really written or run serious code that falls foul of overflow or rounding errors, but they can be very awkward in serious applications.

There were several specious reasons thought up to explain why the executables were of such differing sizes. It is not true that this is a function of the sieve size to any marked degree, as the code and data areas are handled separately. The real reasons are that the efficiency of code generation differs markedly from one compiler to another, and that some implementations build in a great deal more extraneous code than others - you could see this in the smaller executable when some compilers were run in "optimizing" mode. The C and C++ executables differ enormously in size - no doubt due to the vast amounts of code needed to support the iostream library.

The Borland 5.5 and WatCom C/C++ compilers are 32-bit ones, rather than 16-bit ones. But even allowing for this, they suffer from bizarre code bloat for small applications. There may be command line parameters and options that one can set to try to produce tighter code, but I have not bothered to experiment further. Some (most) of the overheads may relate to the fact that they have to produces "Windows" compatible programs. Compilers like this are clearly designed with an "everyone has 1GB of memory and 200GB of disk space, and if they don't they should go and buy more" philosophy.

The "executable" produced from the C# compiler are not true executables in the same sense as those produced by the C++ and Pascal compilers, as the code in them still has to be "Jitted" into its final form.

The limitation imposed by the Parva system on the sieve size is entirely due to the fact that the interpreter system only allows for about 50000 words of memory - which has to hold the pseudo-code and all variables. The limit on the sieve size was about 49000. This could have been extended simply by modifying the interpreter, and then recompiling it, but you were not in a position to do that.

Interestingly, it does not seem to make a difference if the Free Pascal compiler you were using is used in optimizing mode or not. An earlier release used in previous years was quite different - for example the Sieve program compiled to 15872 bytes in ordinary mode and to 14848 bytes in optimized mode.

  .---------------------------------------------------------------------------.
  |                 | Sieve     | Fibo      | Empty     |                     |
  |                 | Code Size | Code Size | Code Size |                     |
  |                 |           |           |           |                     |
  | Free Pascal     |   31 744  |   31 232  |   28 672  | Sieve limit  16410  |
  |-----------------+-----------+-----------+-----------+---------------------|
  | Optimized       |           |           |           |                     |
  | Free Pascal     |   31 744  |   31 232  |   28 672  | Sieve limit  16410  |
  |-----------------+-----------+-----------+-----------+---------------------|
  | Modula-2        |   18 609  |   18 098  |   11 946  | Sieve limit  32770  |
  |-----------------+-----------+-----------+-----------+---------------------|
  | Optimized  M-2  |   18 549  |   18 049  |   11 946  | Sieve limit  32770  |
  |-----------------+-----------+-----------+-----------+---------------------'
  | Borland C       |   66 560  |   66 048  |   52 224  |
  |-----------------+-----------+-----------+-----------|
  | Borland C++     |  149 504  |  148 480  |   47 104  |
  |-----------------+-----------+-----------+-----------|
  | Watcom C        |   37 376  |   36 864  |   27 648  |
  |-----------------+-----------+-----------+-----------|
  | Watcom C++      |   51 712  |   50 688  |   22 528  |
  |-----------------+-----------+-----------+-----------|
  | C#              |   28 672  |   28 672  |   16 896  |
  |-----------------+-----------+-----------+-----------+---------------------.
  | Parva           |    N/A    |    N/A    |    N/A    | Sieve limit  49000  |
  |-----------------+-----------+-----------+-----------+---------------------'
  | Modula-2 via    |   62 976  |   62 464  |   62 464  |
  | Borland C       |           |           |           |
  `-----------------------------------------------------'


The Sieve in Parva

The corrected code is very simple. A few groups got it badly wrong, with braces in the wrong places.

  void main() {
  // Sieve of Eratosthenes for finding primes 2 <= n <= 49000 (Parva version)
  // P.D. Terry,  Rhodes University, 2006
    const Max = 49000;
    bool[] Uncrossed = new bool[Max];         // the sieve
    int i, n, k, it, iterations, primes = 0;  // counters
    read("How many iterations? ", iterations);
    read("Supply largest number to be tested ", n);
    if (n > Max) {
      write("n too large, sorry");
      return;
    }
    it = 1;
    while (it <= iterations) {
      primes = 0;
      write("Prime numbers between 2 and " , n, "\n");
      write("-----------------------------------\n");
      i = 2;
      while (i <= n) {                          // clear sieve
        Uncrossed[i-2] = true;
        i = i + 1;
      }
      i = 2;
      while (i <= n) {                          // the passes over the sieve
        if (Uncrossed[i-2]) {
          if (primes - (primes/8)*8 == 0)
            write("\n");                        // ensure line not too long
          primes = primes + 1;
          write(i, "\t");
          k = i;                                // now cross out multiples of i
          Uncrossed[k-2] = false;
          k = k + i;
          while (k <= n) {
            Uncrossed[k-2] = false;
            k = k + i;
          }
        }
        i = i + 1;
      }
      it = it + 1;
      write("\n");
    }
    write(primes, " primes");
  }


Task 8 - High level translators

Several students complained that the C code generated by the X2C system was "unreadable", and "not what we would have written ourselves". There can be no dispute with the second of those arguments, but if you take a careful look at the generated C code, it is verbose, rather than unreadable, because long identifier names have been used. This is actually not such a bad thing - at least one can tell the "origin" of any identifier, since the original module in which it was declared is incorporated into its name, and this is is a very useful trick, both for large programs, and (more especially) when one has to contend with the miserable rules that C has for controlling identifier name spaces. In fact, in the days when I used Modula regularly, I used a convention similar to this of my own accord, and have carried it over into my other coding, as you will see in several places in the book. Some of the other "unreadability" presumably relates to the fact that the X2C system is obliged to translate the CARDINAL type to the unsigned int type, which is not one some of you will ever have used - this explains all those funny casts and capital Us that you saw. Some people commented that "maintaining the C code generated would be a nightmare". Well, maybe, but the point of using a tool like this is that you can develop and maintain your programs in Modula-2 and then simply convert them to C when you want to get them compiled on some other machine. So normally a user of Xtacy would not read or edit the C code at all!


Task 9 - How fast/slow are various implementations?

The times (seconds) taken to execute the various programs are shown below (figures in brackets are for runs on my 1.04GHz laptop, others for the 3.00 GHz lab machines). In all cases the systems ran on Windows XP.

We note several points of interest:

(a) The Parva interpreted system is about two orders of magnitude slower than the native-code systems. Even here we can see the benefits of using an optimizing system, simple though this is (later we shall discuss this in more detail).

(b) In deriving these figures some experimentation was first needed so as to find parameters that would yield times sufficiently long to make comparisons meaningful. The times were obtained by simple use of a stopwatch, and of course there is always an element of reaction time in such measurements. The output statements were commented out so that all that was really being measured was the time for the algorithms themselves.

(c) The Java system, when JITed, is way better than when the JVM runs in pure interpreter mode.

(d) Even allowing for the reaction time phenomenon, there are some strange anomalies here. One might expect the execution times to be very closely related to the processor clock speeds, and that the ratio of times measured on the laptop and the lab machines for each application would have been the same, but clearly they are not. I expect that the differences - which are quite marked - can be put down to the different interior architectures of the processors themselves, but I have not had time to explore this further.

  .--------------------------------------------------------------.
  | Sieve: Iterations   10 000 | Size of sieve  16 000           |
  |--------------------------------------------------------------|
  | Fibo:  Upper limit   40                    |                 |
  |--------------------------------------------+-----------------|
  |                          |    Sieve        |    Fibo         |
  |--------------------------+-----------------+-----------------|
  | Free Pascal              |  (9.2)    4.4   |  (12.7)   4.2   |
  |--------------------------+-----------------+-----------------|
  | Free Pascal (optimized)  |  (8.6)    4.2   |  (12.3)   4.1   |
  |--------------------------+-----------------+-----------------|
  | Modula-2                 |  (5.7)    2.4   |                 |
  |--------------------------+-----------------+-----------------|
  | Modula-2 (optimized)     |  (2.3)    1.8   |  (23.5)  32.3   |
  |--------------------------+-----------------+-----------------|
  | C                        |  (3.8)    2.2   |  (12.3)   3.9   |
  |--------------------------+-----------------+-----------------|
  | C++                      |  (4.1)    2.1   |  (12.2)   4.0   |
  |--------------------------+-----------------+-----------------|
  | Modula-2 (via C)         | (25.2)    6.3   |  (18.9)   3.9   |
  |--------------------------+-----------------+-----------------|
  | C#                       |  (3.7)    3.2   |   (9.8)   5.1   |
  |--------------------------+-----------------+-----------------|
  | Java       (with JIT)    |  (6.6)    3.0   |   (9.3)   2.7   |
  |--------------------------+-----------------+-----------------|
  | Java -Xint (interpret)   | (74.3)   46.6   |  (92.6)  48.2   |
  |--------------------------+-----------------+-----------------|
  | Parva                    | (1080)  448.0   |  (692)  277.0   |
  |--------------------------+-----------------+-----------------|
  | Parva (optimized)        | (810.0) 360.0   |         225.0   |
  `--------------------------------------------------------------'


Task 11 Something more creative - Best of British Luck

This can be handled quite easily. The solution below illustrates the use of substring() as well as of stringTokenizer(). Points missed were that a single conversion algorithm works for conversion in either direction, and that there might be any number of dot-separated components of the name and address. Once again the program should be able to handle input data that, strictly speaking, is incorrect.

  // Convert Internet  <---> Janet addresses
  // P.D. Terry, Rhodes University, 2006

  import java.util.*;
  import Library.*;

  class Internet {

    static String convert(String address) {
    // Returns opposite form of address
      int i = address.indexOf('@');
      String user = address.substring(0, i+1);
      address = address.substring(i+1);
      StringTokenizer tokens = new StringTokenizer(address, ".", true);
      address = "";
      while (tokens.hasMoreTokens())
        address = tokens.nextToken() + address;
      return user + address;
    }

    public static void main (String[] args) {
    // first check that commandline arguments have been supplied
    // attempt to open data file
    // attempt to open results file
    // all this as in SampleIO.java - see full solution for details

    // read and process data file
      while (true) {
        String address = data.readWord();
        if (data.noMoreData()) break;
        results.writeLine(convert(address));
      }

    // close results file safely
      results.close();
    }

  }

Okay, I'll 'fess up. When I first set this exercise I thought it might be fun to use the StringBuffer class and the Stack class, and came up with this:

    static String convert(String address) {
    // Returns opposite form of address
      Stack st = new Stack();
      StringBuffer sb = new StringBuffer();
      StringTokenizer tokens = new StringTokenizer(address, ".@", true);
      String t;
      do {
        t = tokens.nextToken(); sb.append(t);
      } while (tokens.hasMoreTokens() && !t.equals("@"));
      while (tokens.hasMoreTokens()) st.push(tokens.nextToken());
      while (!st.empty()) sb.append(st.pop());
      return sb.toString();
    }

but, as already mentioned, there is always a simpler way!


Task 12 Creative programming - How long will my journey take?

The main point of this exercise was to give some exposure to the ArrayList class, which we shall use repeatedly later on as a simple container class for building up symbol tables and the like. For ease of use the little Station class in the code below has exposed its data members as "public", thus eliminating the need for "getter" methods.

  // Set up a poster of travel times between any two stations on a suburban system
  // Data is of the form
  //
  //   College 8 Hamilton 5 Oakdene 12 Gino's 25 Mews 9 Union 12 Steers 17 Athies
  //
  // P.D. Terry, Rhodes University, 2006

  import Library.*;
  import java.util.*;

  class Station {
    public String name;
    public int toNext;

    public Station(String name, int toNext) {
      this.name = name;
      this.toNext = toNext;
    }

  } // Station

  class Poster {

    public static void main(String[] args) {
      ArrayList list = new ArrayList();
      int i, j, toNext;

      //              Construct list of stations and travel times

      do {
        String stationName = IO.readWord();
        toNext = IO.readInt();
        if (IO.noMoreData()) toNext = 0;
        list.add(new Station(stationName, toNext));
      } while (toNext > 0);

      //              Construct symmetric matrix of accumulated travel times

      int[][] matrix = new int[list.size() + 1] [list.size() + 1];
      for (i = 0; i <= list.size(); i++) {
        matrix[i][i] = 0;
        for (j = i + 1; j < list.size() + 1; j++)
          matrix[j][i] = matrix[i][j] = matrix[i][j-1] + ((Station)list.get(j-1)).toNext;
      }

      //              Output station names and matrix

      IO.write(" ", 12);
      for (i = 0; i < list.size(); i++) IO.write(((Station)list.get(i)).name, 10);
      IO.writeLine();
      IO.writeLine();
      for (i = 0; i < list.size(); i++) {
        IO.write(((Station) list.get(i)).name, -10);
        for (j = 0; j < list.size(); j++) IO.write(matrix[i][j], 10);
        IO.writeLine();
      }
    }

  }


Task 13 - Goldbach's Conjecture.

Most submissions had grasped the concept of setting up a set to contain the prime numbers, but there was sometimes very tortuous/confused code thereafter for the very simple task of trying to find whether an even number could be expressed as the sum of two of those primes. You only need one loop for each attempt - if N is to be expressed as the sum of two numbers A and B, then there is no need to try out all possible combinations of A and B (since B must = N - A). Additionally, we need only try values for A from 2 to N/2 (think about it!). One way of programming this exercise would be as below. Note the way in which the sieve has been constructed from a simple adaptation of the code given to you earlier. There is no need for the primes method to do any output, or even to count how many prime numbers are added to the set.

  import Library.*;
  import java.util.*;

  class Goldbach {
  // Sieve of Eratosthenes for testing Goldbach's conjecture
  // P.D. Terry,  Rhodes University, 2006

    public static void main(String [] args) {
      IO.write("Supply largest number to be tested ");
      int limit = IO.readInt();        // limit of test
      SymSet primeSet = primes(limit);
      boolean Goldbach = true;         // optimistic
      int test = 4;
      while (Goldbach && test <= limit) {
        boolean found = false;         // try to find the pair
        int i = 2;
        while (i <= test / 2 && !found) {
          if (primeSet.contains(i) && primeSet.contains(test - i)) {
            found = true;
            IO.writeLine(" " + test + "\t" + i + "\t" + (test - i));
          }
          else i++;
        }
        if (!found) {
          IO.writeLine("conjecture fails for ", test);
          Goldbach = false;
        }
        test = test + 2;               // move on to next even number
      }
      IO.writeLine("Conjecture seems to be " + Goldbach);   // final result of test
    }

    static SymSet primes(int max)  {
    // Returns the set of prime numbers smaller than max
      SymSet primeSet = new SymSet();  // the prime numbers
      SymSet crossed = new SymSet();   // the sieve
      for (int i = 2; i <= max; i++) { // the passes over the sieve
        if (!crossed.contains(i)) {
          primeSet.incl(i);
          int k = i;                   // now cross out multiples of i
          do {
            crossed.incl(k);
            k += i;
          } while (k <= max);
        }
      }
      return primeSet;
    }

  }


Home  © P.D. Terry