25-Comp-A4 Program Design and Data Structures · May 2013
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer)
National Exams — May 2013 — 98-Comp-A4 Program Design and Data Structures. Three-hour, closed-book exam, no calculator permitted. Format: eight questions, candidates answer any five (all questions equal weight; only the first five appearing in the answer book are marked). Pseudocode or a high-level language (C or C++) is acceptable throughout — marking emphasizes program operation, not syntactic detail. All eight questions are solved below for completeness. No marks breakdown per sub-part is given on the source paper beyond the "equal weight" instruction.
Reference texts: Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms (3rd ed., MIT Press) — algorithm design, complexity analysis, sorting; Weiss, Data Structures and Algorithm Analysis in C (2nd ed., Pearson) — linked lists, stacks, pointer-based structures; Deitel & Deitel, C++ How to Program (9th ed., Pearson) — classes, templates, operator overloading; Kernighan & Ritchie, The C Programming Language (2nd ed.) — file I/O and arrays.
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 positive integer, read as a sequence of decimal digits. Find. Whether, for every digit position $p$ (0-indexed from the left), the digit stored there equals the count of digit $p$ occurring anywhere in the number.
Approach. Read the number as a string (or repeatedly divide/mod by 10 into an array), then for every position count occurrences of that position's own index value across the whole array and compare.
#define MAXLEN 16
int is_self_describing(int digits[], int len) {
for (int pos = 0; pos < len; pos++) {
int count = 0;
for (int i = 0; i < len; i++)
if (digits[i] == pos) count++;
if (count != digits[pos]) return 0; /* fails at this position */
}
return 1;
}
int main(void) {
char buf[MAXLEN + 1];
int digits[MAXLEN], len;
printf("Enter a positive integer: ");
scanf("%s", buf);
len = 0;
for (int i = 0; buf[i] != '\0'; i++)
digits[len++] = buf[i] - '0';
if (is_self_describing(digits, len))
printf("%s is self-describing.\n", buf);
else
printf("%s is NOT self-describing.\n", buf);
return 0;
}
| Input | Self-describing? | Why |
|---|---|---|
| 2020 | Yes | pos0=2 (two 0's), pos1=0 (no 1's), pos2=2 (two 2's), pos3=0 (no 3's) |
| 1210 | Yes | pos0=1 (one 0), pos1=2 (two 1's), pos2=1 (one 2), pos3=0 (no 3's) |
| 3211000 | Yes | 7-digit family member: pos0=3, pos1=2, pos2=1, pos3..6=1,0,0,0 |
| 1234 | No | pos0=1 but there are zero 0's in the number |