Nivaar Exam Prep

25-Comp-A4 Program Design and Data Structures · December 2016

Question 2 of 9: Programming — Line Reversal and Three-Way Coordinate Sorting

Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer) · Last updated

Notes on this paper

Pseudocode or any high-level language is accepted, and the examiner's note states explicitly that marking emphasises the operation of the program, not syntactic details.

Reference texts for this subject.

  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 4th ed. — tree traversals and BSTs (ch. 12), sorting (ch. 2, 7), asymptotic analysis (ch. 3).
  • Weiss, Data Structures and Algorithm Analysis in C, 2nd ed. — linked lists and queues (ch. 3), binary search trees (ch. 4).
  • Deitel & Deitel, C++ How to Program, 10th ed. — class design and templates (ch. 9–12), file streams (ch. 14), operator overloading (ch. 11).
  • Kernighan & Ritchie, The C Programming Language, 2nd ed. — character/array I/O idioms (ch. 1, 7), pointers, structures and linked lists (ch. 5–6).
  • Stroustrup, The C++ Programming Language, 4th ed. — class templates and value semantics (ch. 3, 25–27).

The Computer Engineering citation list is built around architecture and networking texts (Patterson & Hennessy, Tanenbaum, Mano); this subject is programming and data structures, so the works above are cited instead.

Question 2: Programming — Line Reversal and Three-Way Coordinate Sorting (20 marks: (a) 10, (b) 10)

Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.

Given. (a) A stream of text lines terminated by an empty line. (b) 20 $(x,y)$ coordinate pairs.

Find. (a) The reverse of every line, printed as it is entered. (b) The same 20 pairs sorted three different ways (each independent of the others — a fresh sort of the original data, not a chain).

Approach. (a) Read a full line, print its characters from last to first, and use the empty-line length as the loop's own termination test. (b) Store all 20 pairs once in one array and call a generic sort three times, once per comparator (increasing x, decreasing y, increasing $x^2+y^2$), so the original readings are reused rather than re-entered.

(a) Reverse a line of text (10 marks)

  1. Write the program.
    #include <stdio.h>
    #include <string.h>
    
    #define MAXLINE 200
    
    int main(void)
    {
        char line[MAXLINE];
        int len, i;
    
        for (;;) {
            printf("enter a line of text: ");
            if (fgets(line, MAXLINE, stdin) == NULL) break;
            len = (int)strlen(line);
            if (len > 0 && line[len - 1] == '\n') line[--len] = '\0';
            if (len == 0) break;                    /* empty line: stop */
    
            printf("the reversed line is: ");
            for (i = len - 1; i >= 0; i--) putchar(line[i]);
            putchar('\n');
        }
        return 0;
    }
    Checking against the paper's example, "Computer programming is fun." printed back to front is ".nuf si gnimmargorp retupmoC", and "CN Tower" reverses to "rewoT NC" — both are exactly character-by-character mirrors of the input, which is all this loop does.

(b) Sort 20 coordinate pairs three ways (10 marks)

  1. Store the pairs once; sort with three different comparators covering (i), (ii) and (iii). Using the C standard library's qsort with a swappable comparison function avoids writing three separate sort routines — only the three-line comparator changes between calls, and each call re-sorts a fresh copy of the same original 20 pairs: (i) increasing x uses by_x_increasing, (ii) decreasing y uses by_y_decreasing, and (iii) increasing distance from the origin uses by_distance_increasing.
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct { double x, y; } Point;
    #define N 20
    
    int by_x_increasing(const void *a, const void *b) {
        double dx = ((const Point *)a)->x - ((const Point *)b)->x;
        return (dx > 0) - (dx < 0);
    }
    int by_y_decreasing(const void *a, const void *b) {
        double dy = ((const Point *)b)->y - ((const Point *)a)->y;
        return (dy > 0) - (dy < 0);
    }
    double dist2(const Point *p) { return p->x * p->x + p->y * p->y; }
    int by_distance_increasing(const void *a, const void *b) {
        double dd = dist2((const Point *)a) - dist2((const Point *)b);
        return (dd > 0) - (dd < 0);
    }
    
    int main(void)
    {
        Point pts[N], work[N];
        int i;
    
        for (i = 0; i < N; i++) scanf("%lf %lf", &pts[i].x, &pts[i].y);
    
        memcpy(work, pts, sizeof pts);
        qsort(work, N, sizeof(Point), by_x_increasing);
        printf("(i) Increasing x:\n");
        for (i = 0; i < N; i++) printf("  (%.2f, %.2f)\n", work[i].x, work[i].y);
    
        memcpy(work, pts, sizeof pts);
        qsort(work, N, sizeof(Point), by_y_decreasing);
        printf("(ii) Decreasing y:\n");
        for (i = 0; i < N; i++) printf("  (%.2f, %.2f)\n", work[i].x, work[i].y);
    
        memcpy(work, pts, sizeof pts);
        qsort(work, N, sizeof(Point), by_distance_increasing);
        printf("(iii) Increasing distance from origin:\n");
        for (i = 0; i < N; i++) printf("  (%.2f, %.2f)\n", work[i].x, work[i].y);
        return 0;
    }
    Comparing squared distance $x^2+y^2$ instead of $\sqrt{x^2+y^2}$ avoids 20 unnecessary square-root calls, since the square root is monotonic and does not change the sorted order.
Question 2 — results
PartBehaviour
(a) "Computer programming is fun.".nuf si gnimmargorp retupmoC
(a) "CN Tower"rewoT NC
(b) Sort keys usedx asc, y desc, $x^2+y^2$ asc (no sqrt needed)