Cambridge IAL · Thinka-original Practice Paper

2025 Cambridge IAL Computer Science (9618) Practice Paper with Answers

Thinka Jun 2025 (V3) Cambridge International A Level-Style Mock — Computer Science (9618)

300 marks450 mins2025
An original Thinka practice paper modelled on the structure and difficulty of the Jun 2025 (V3) Cambridge International A Level Computer Science (9618) paper. Not affiliated with or reproduced from Cambridge.

Paper 1 Theory Fundamentals

Answer all questions. Calculators must not be used. Write your answers in the space provided on the question paper.
7 Question · 74.9 marks
Question 1 · Short Answer & Conversions
10.7 marks
Convert the denary value \(-11.625\) into an 8-bit signed two's complement fixed-point binary format, where 5 bits are allocated for the integer part (including the sign bit) and 3 bits are allocated for the fractional part. Show your working.
Show answer & marking scheme

Worked solution

To convert \(-11.625\) using 5 integer bits and 3 fractional bits:

1. Convert the positive value \(11.625\) to binary first:
- Integer part: \(11 = 8 + 2 + 1 = 01011_2\) (using 5 bits)
- Fractional part: \(0.625 = 0.5 + 0.125 = 101_2\) (using 3 bits)
- Combine: \(01011.101_2\)

2. Convert to negative using two's complement:
- Invert the bits of \(01011101\): \(10100010\)
- Add 1 to the least significant bit (LSB): \(10100010 + 00000001 = 10100011\)

3. Verify the representation:
- Weights: \(-16, 8, 4, 2, 1, 0.5, 0.25, 0.125\)
- \(10100011_2 = -16 + 4 + 0.25 + 0.125 = -11.625\)

Marking scheme

Award marks as follows:
- 3 marks: Converting the integer part of the positive number to binary (01011) (Method mark)
- 2 marks: Converting the fractional part of the positive number to binary (101) (Method mark)
- 3 marks: Showing the two's complement step (inverting bits and adding 1) (Method mark)
- 2.7 marks: Final correct 8-bit binary representation (10100011) (Accuracy mark)
Question 2 · Short Answer & Conversions
10.7 marks
An unnormalised database table `UNNORMALISED_ATHLETE` is defined as follows:
`UNNORMALISED_ATHLETE(AthleteID, AthleteName, HouseColor, EventID, EventName, EventCategory, Score)`
with a composite primary key of `(AthleteID, EventID)`.

1. Explain why this table is not in Second Normal Form (2NF).
2. Design a set of Third Normal Form (3NF) relational schemas for this database. Use the notation: `TableName(Attribute1, Attribute2, ...)` and underline the primary keys.
Show answer & marking scheme

Worked solution

1. The table is not in 2NF because it contains partial functional dependencies. A relation is in 2NF if it is in 1NF and contains no partial key dependencies. Here, non-key attributes `AthleteName` and `HouseColor` depend only on part of the composite key (`AthleteID`), while `EventName` and `EventCategory` depend only on `EventID`.

2. To achieve 3NF, the dependencies must be separated into individual tables:
- `ATHLETE(AthleteID, AthleteName, HouseColor)` where `AthleteID` is the primary key.
- `EVENT(EventID, EventName, EventCategory)` where `EventID` is the primary key.
- `PERFORMANCE(AthleteID, EventID, Score)` where `(AthleteID, EventID)` is the composite primary key, with `AthleteID` and `EventID` acting as foreign keys referencing their respective tables.

Marking scheme

Award marks as follows:
- 4 marks: Explanation of partial dependency (identifying that non-key attributes depend on only part of the primary key, with specific examples from the scenario).
- 6.7 marks: Correct identification and notation of the 3NF schemas (2 marks for ATHLETE, 2 marks for EVENT, 2.7 marks for PERFORMANCE, including underlining primary keys).
Question 3 · Short Answer & Conversions
10.7 marks
An assembly language program consists of the following consecutive instructions:
```
LDD 200
ADD 201
STO 202
LDI 202
```

Describe the complete execution sequence of these four instructions, including how addressing modes (Direct and Indirect) affect the operands and the Accumulator (ACC). The memory currently contains:
- Address 200: Value 15
- Address 201: Value 32
- Address 202: Value 200
Show answer & marking scheme

Worked solution

1. `LDD 200`: Direct addressing. The processor loads the actual value stored at memory address 200 into the Accumulator. ACC = 15.
2. `ADD 201`: Direct addressing. The processor fetches the value stored at memory address 201 (which is 32) and adds it to the ACC. ACC = 15 + 32 = 47.
3. `STO 202`: Direct addressing. The value currently in the Accumulator (47) is stored in memory address 202. The previous value at 202 (200) is overwritten by 47.
4. `LDI 202`: Indirect addressing. The processor accesses address 202 to find the target address. The target address is 47. The processor then retrieves the value stored at address 47 and loads it into the ACC.

Marking scheme

Award marks as follows:
- 2.5 marks: Correctly explaining `LDD 200` loading 15 into ACC.
- 2.5 marks: Correctly explaining `ADD 201` adding 32 to ACC resulting in 47.
- 2.5 marks: Correctly explaining `STO 202` saving value 47 into address 202.
- 3.2 marks: Correctly explaining indirect addressing for `LDI 202` (fetching pointer 47 from address 202, and attempting to load the value at address 47).
Question 4 · Short Answer & Conversions
10.7 marks
An IPv4 address is specified using Classless Inter-Domain Routing (CIDR) notation as `192.168.4.135/26`.

1. Represent the subnet mask in dotted decimal notation.
2. Calculate the network address for this subnet. Show your binary working for the final octet.
Show answer & marking scheme

Worked solution

1. The `/26` notation means the first 26 bits of the subnet mask are 1s:
- Binary: `11111111.11111111.11111111.11000000`
- Conversion to dotted decimal: `255.255.255.192`

2. To find the network address, perform a bitwise AND operation on the IP address and the subnet mask. Only the fourth octet differs from 255 or 0:
- IP address fourth octet: \(135 = 10000111_2\)
- Subnet mask fourth octet: \(192 = 11000000_2\)
- Bitwise AND: \(10000111_2 \text{ AND } 11000000_2 = 10000000_2\)
- Convert back to denary: \(10000000_2 = 128\)
- Thus, the network address is `192.168.4.128`.

Marking scheme

Award marks as follows:
- 4 marks: Correct subnet mask of 255.255.255.192 with working shown.
- 3 marks: Showing the binary representation of the fourth octet of both the IP (10000111) and the mask (11000000).
- 3.7 marks: Correct bitwise AND operation resulting in the final network address of 192.168.4.128.
Question 5 · Short Answer & Conversions
10.7 marks
State three differences between the way a compiler and an interpreter translate and execute program code. Explain which of these language translators is more suitable during the development phase of a software application.
Show answer & marking scheme

Worked solution

Differences:
1. Translation Unit: A compiler translates the entire source code file into a standalone machine-code executable file (object code) at once, whereas an interpreter translates and executes source code line-by-line.
2. Execution Speed: Compiled programs execute much faster since no translation occurs at runtime, whereas interpreted programs run slower because translation must happen dynamically during execution.
3. Error Detection: A compiler scans the entire code and reports all compilation errors at the end, while an interpreter halts execution immediately upon encountering the first runtime error.

Suitability for software development:
An interpreter is more suitable because it allows for rapid prototyping, debugging, and testing. Code changes can be executed immediately without having to wait for a lengthy re-compilation process, and immediate halts highlight exactly which line caused an error.

Marking scheme

Award marks as follows:
- 6 marks: 2 marks for each of the three clearly explained differences between compilers and interpreters.
- 1.7 marks: Stating that an interpreter is more suitable for the development phase.
- 3 marks: Justifying the choice by mentioning rapid debugging, instant execution, and precise location of runtime errors.
Question 6 · Short Answer & Conversions
10.7 marks
A secure file transfer system must send a sensitive document over an insecure network. Describe how asymmetric encryption and digital signatures are applied together to guarantee both data confidentiality and authenticity of the sender.
Show answer & marking scheme

Worked solution

To establish both confidentiality and authenticity, the process is as follows:

Authenticity (Digital Signature creation):
1. The sender runs the original document through a hashing algorithm to produce a unique message digest.
2. The sender encrypts this digest with their own private key, creating a digital signature.
3. The signature is appended to the document.

Confidentiality:
4. The combined package (document + digital signature) is encrypted using the recipient's public key.
5. Only the recipient's private key can decrypt this package, ensuring confidentiality.

Verification:
6. The recipient decrypts the package using their private key.
7. The recipient decrypts the digital signature using the sender's public key to retrieve the original digest.
8. The recipient hashes the decrypted document and compares it to the original digest. A match verifies that the document has not been altered (integrity) and came from the sender (authenticity).

Marking scheme

Award marks as follows:
- 3 marks: For detailing the creation of the digital signature (hashing + encrypting with sender's private key).
- 3 marks: For explaining how confidentiality is achieved (encrypting with recipient's public key).
- 4.7 marks: For explaining the verification process on the recipient's side (decrypting with recipient's private key, decrypting the signature with sender's public key, and comparing hashes).
Question 7 · Short Answer & Conversions
10.7 marks
Compare the licensing conditions of open-source software and shareware. In your answer, address access to the source code, pricing structures, and rights of modification.
Show answer & marking scheme

Worked solution

The comparison can be broken down as follows:

1. Access to Source Code:
- Open-source: The source code is freely available to view, modify, and inspect by anyone.
- Shareware: The source code is closed-source (proprietary) and not distributed to the user; only compiled binaries are provided.

2. Pricing and Cost:
- Open-source: Usually free of charge to download and use, though some creators charge for commercial support.
- Shareware: Provided free of charge for a limited evaluation period, after which users are required to purchase a full license/registration key.

3. Rights to Modify and Redistribute:
- Open-source: Users have the explicit right to modify the source code and redistribute their custom versions (often governed by licenses like GPL).
- Shareware: Users are not permitted to modify the software or distribute altered versions. Copying and distributing the original evaluation copy is permitted, but the core software is copyright-protected and closed.

Marking scheme

Award marks as follows:
- 3 marks: Comparing source code access (open-source is accessible, shareware is closed-source).
- 3.7 marks: Comparing cost terms (open-source is free/unrestricted, shareware requires a trial-period payment).
- 4 marks: Comparing modification and redistribution rights (open-source permits changes and customized distribution, shareware strictly prohibits software modification).

Paper 2 Problem Solving & Programming

Answer all questions. Write your solutions in standard Cambridge pseudocode. Refer to the enclosed insert.
7 Question · 74.9 marks
Question 1 · Pseudocode Construction & Tracing
10.7 marks
A student has written the following pseudocode algorithm to sort a small list of numbers.

```pseudocode
PROCEDURE ProcessArray(BYREF Arr : ARRAY OF INTEGER, Size : INTEGER)
DECLARE i, Temp : INTEGER
i <- 1
WHILE i < Size
IF Arr[i] > Arr[i+1] THEN
Temp <- Arr[i]
Arr[i] <- Arr[i+1]
Arr[i+1] <- Temp
IF i > 1 THEN
i <- i - 1
ELSE
i <- i + 1
ENDIF
ELSE
i <- i + 1
ENDIF
ENDWHILE
ENDPROCEDURE
```

Trace the execution of this procedure when called as follows:

```pseudocode
DECLARE TestArray : ARRAY[1:4] OF INTEGER
TestArray[1] <- 4
TestArray[2] <- 2
TestArray[3] <- 7
TestArray[4] <- 1
ProcessArray(TestArray, 4)
```

Complete the trace table showing how the values of the variables and array elements change during execution. Enter a new row whenever a variable or array element is modified.
Show answer & marking scheme

Worked solution

Execution Step-by-Step:
1. Initial state: `i = 1`, `Temp = null`, `Arr = [4, 2, 7, 1]`
2. `i = 1`: `Arr[1] > Arr[2]` (4 > 2) is TRUE. `Temp <- 4`, `Arr[1] <- 2`, `Arr[2] <- 4`. Since `i > 1` is FALSE, `i` is incremented to 2.
3. `i = 2`: `Arr[2] > Arr[3]` (4 > 7) is FALSE. `i` is incremented to 3.
4. `i = 3`: `Arr[3] > Arr[4]` (7 > 1) is TRUE. `Temp <- 7`, `Arr[3] <- 1`, `Arr[4] <- 7`. Since `i > 1` is TRUE, `i` is decremented to 2.
5. `i = 2`: `Arr[2] > Arr[3]` (4 > 1) is TRUE. `Temp <- 4`, `Arr[2] <- 1`, `Arr[3] <- 4`. Since `i > 1` is TRUE, `i` is decremented to 1.
6. `i = 1`: `Arr[1] > Arr[2]` (2 > 1) is TRUE. `Temp <- 2`, `Arr[1] <- 1`, `Arr[2] <- 2`. Since `i > 1` is FALSE, `i` is incremented to 2.
7. `i = 2`: `Arr[2] > Arr[3]` (2 > 4) is FALSE. `i` is incremented to 3.
8. `i = 3`: `Arr[3] > Arr[4]` (4 > 7) is FALSE. `i` is incremented to 4.
9. `i = 4`: Loop terminates because `i < Size` (4 < 4) is FALSE.

Marking scheme

- 1 mark for initial row correctly initialized.
- 3 marks for correct sequencing of the pointer variable `i` (increasing and decreasing correctly).
- 3 marks for correct array assignments (swapping values step-by-step).
- 2 marks for correct updates of `Temp`.
- 1.7 marks for stopping the trace exactly when `i` reaches 4.
Question 2 · Pseudocode Construction & Tracing
10.7 marks
Write pseudocode for a function `ExtractDomain() RETURNS INTEGER` that reads email addresses from an existing text file named `emails.txt`.

Each line of the file contains a single email address. The function must extract the domain name (the part of the email address following the `'@'` symbol) for each valid email.

An email address is considered valid for extraction only if:
1. It contains exactly one `'@'` character.
2. The `'@'` character is neither the first nor the last character of the email address.

The function must write unique valid domain names to a new text file named `domains.txt`. To do this, use a local 1D array `UniqueDomains` of size 100 of type `STRING` to keep track of domain names already written to `domains.txt`.

The function must:
- Open both files with appropriate modes.
- Process the input file line-by-line until the end of the file is reached.
- Perform validation checks on each email address.
- Ensure that no duplicate domain names are written to `domains.txt`.
- Count the total number of unique valid domains found and written.
- Close both files and return the count.

You can assume standard string functions are available:
- `LENGTH(StringVal : STRING) RETURNS INTEGER`
- `MID(StringVal : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING`
Show answer & marking scheme

Worked solution

The solution opens `emails.txt` for reading and `domains.txt` for writing. It loops through the file line by line. For each line, it calculates the length and finds how many `@` characters exist and where the last one is. If it matches the validation criteria (exactly one, not first or last), it extracts the substring after the `@` symbol. It then searches the `UniqueDomains` array to ensure the domain hasn't been written yet. If unique, it adds it to the array, writes it to `domains.txt`, and increments the count. Finally, it closes the files and returns the count.

Marking scheme

- 1 mark: Correct function header and return type declaration.
- 1.7 marks: Open and close both files in correct modes.
- 2 marks: Correct logic to count and find the position of the `@` symbol.
- 1 mark: Correct validation logic (at count = 1 and position not at limits).
- 2 marks: Correctly extracting domain using MID().
- 2 marks: Loop to check for duplicates in array prior to writing.
- 1 mark: Writing unique domain and updating/returning count.
Question 3 · Pseudocode Construction & Tracing
10.7 marks
A circular queue is implemented using a 1D array and three global variables:
- `QueueArray : ARRAY[1:8] OF STRING`
- `FrontPointer : INTEGER` (points to the index of the first element in the queue)
- `RearPointer : INTEGER` (points to the index of the last element in the queue)
- `QueueLength : INTEGER` (stores the current number of elements in the queue)

Initially, the queue is empty. `FrontPointer` is initialized to 1, `RearPointer` is initialized to 0, and `QueueLength` is initialized to 0.

Write the pseudocode for a function `Enqueue(NewItem : STRING) RETURNS BOOLEAN` which:
- Checks if the queue is full. If the queue is full, it must not add the item and must return `FALSE`.
- Updates `RearPointer` to the next logical index in the circular array.
- Inserts `NewItem` at the new `RearPointer` position.
- Increments `QueueLength`.
- Returns `TRUE` to indicate a successful insertion.

Do not use any other global variables. Ensure that the circular nature of the queue is correctly handled.
Show answer & marking scheme

Worked solution

The function first checks if `QueueLength` has reached the maximum size of the array, which is 8. If so, it returns `FALSE` immediately because of overflow. Otherwise, it increments `RearPointer`. Since the queue is circular, if `RearPointer` exceeds 8, it wraps around to 1. The item is then placed in `QueueArray` at the `RearPointer` position, `QueueLength` is incremented by 1, and the function returns `TRUE`.

Marking scheme

- 1.7 marks: Correct function header and return type definition.
- 2 marks: Accurate overflow check using `QueueLength`.
- 3 marks: Correctly updating `RearPointer` with circular wrap-around logic.
- 2 marks: Storing `NewItem` at the updated index and incrementing `QueueLength`.
- 2 marks: Correctly returning `TRUE` and `FALSE` respectively.
Question 4 · Pseudocode Construction & Tracing
10.7 marks
The recursive function `Mystery` is defined as follows:

```pseudocode
FUNCTION Mystery(n : INTEGER, k : INTEGER) RETURNS INTEGER
IF k = 0 OR k = n THEN
RETURN 1
ELSE
IF k > n THEN
RETURN 0
ELSE
RETURN Mystery(n - 1, k - 1) + Mystery(n - 1, k)
ENDIF
ENDIF
ENDFUNCTION
```

Show the recursive trace or tree of function calls that occurs when `Mystery(4, 2)` is called, state the final return value, and identify the mathematical purpose of this function.
Show answer & marking scheme

Worked solution

Let's expand the execution step by step:
- `Mystery(4, 2)` returns `Mystery(3, 1) + Mystery(3, 2)`
- `Mystery(3, 1)` returns `Mystery(2, 0) + Mystery(2, 1)`
- `Mystery(2, 0)` returns `1` (since k = 0)
- `Mystery(2, 1)` returns `Mystery(1, 0) + Mystery(1, 1)`
- `Mystery(1, 0)` returns `1` (k = 0)
- `Mystery(1, 1)` returns `1` (k = n)
- Thus `Mystery(2, 1)` = 1 + 1 = 2
- Thus `Mystery(3, 1)` = 1 + 2 = 3
- `Mystery(3, 2)` returns `Mystery(2, 1) + Mystery(2, 2)`
- `Mystery(2, 1)` evaluates to 2 (same as above)
- `Mystery(2, 2)` returns `1` (since k = n)
- Thus `Mystery(3, 2)` = 2 + 1 = 3
- Thus `Mystery(4, 2)` = 3 + 3 = 6.

Marking scheme

- 4 marks: Correctly structured recursion tree displaying all 9 function calls.
- 2.7 marks: Correct return values for base cases (leaves of the tree).
- 2 marks: Correct final return value of 6.
- 2 marks: Correct identification of the mathematical concept (combinations / binomial coefficient / Pascals triangle).
Question 5 · Pseudocode Construction & Tracing
10.7 marks
An integer grid is represented by a 2D array `Grid : ARRAY[1:10, 1:10] OF INTEGER`.
The array is sorted as follows:
- Each row is sorted in ascending order from left to right.
- Each column is sorted in ascending order from top to bottom.

An efficient search algorithm begins at the top-right corner of the grid (Row 1, Column 10):
- If the current cell value matches the target value `Target`, the search succeeds.
- If the current cell value is greater than `Target`, move left (decrement the column index).
- If the current cell value is less than `Target`, move down (increment the row index).

Write pseudocode for a function `SearchGrid(Target : INTEGER) RETURNS BOOLEAN` that implements this search algorithm. If the target is found, it must output a message containing the row and column and return `TRUE`. If not found, it must output a "Not Found" message and return `FALSE`.
Show answer & marking scheme

Worked solution

The function initialises two index pointers: `Row` to 1 and `Col` to 10 (the top-right corner). In a `WHILE` loop, it checks if the pointers are within bounds and if the element has not been found. If `Grid[Row, Col]` matches `Target`, it sets `Found` to `TRUE`. If the grid value is larger, it narrows the search space by moving left (`Col <- Col - 1`). If the grid value is smaller, it moves down (`Row <- Row + 1`). Finally, it outputs the result and returns the appropriate boolean.

Marking scheme

- 1.7 marks: Correct function header and return type.
- 2 marks: Correct initialization of search pointer variables to (1, 10).
- 2 marks: Loop termination condition that respects boundaries and `Found` status.
- 2 marks: Conditional checks to navigate the 2D grid correctly.
- 1.5 marks: Print output stating where the target was found, or if it was not.
- 1.5 marks: Return `TRUE` or `FALSE` accordingly.
Question 6 · Pseudocode Construction & Tracing
10.7 marks
A programmer defines a user-defined record type `Book` as follows:

```pseudocode
TYPE Book
DECLARE ISBN : STRING
DECLARE Title : STRING
DECLARE BorrowCount : INTEGER
ENDTYPE
```

An array of these records is declared as:
`DECLARE BookList : ARRAY[1:50] OF Book`

Write pseudocode for a procedure `SortBooks()` that sorts the array `BookList` in descending order of `BorrowCount` using a bubble sort algorithm. If two books have the same `BorrowCount`, the procedure must sort them in alphabetical (ascending) order of their `Title` field. Use standard bubble sort optimizations where appropriate.
Show answer & marking scheme

Worked solution

The procedure implements an optimized bubble sort. The outer loop is a `REPEAT...UNTIL` loop that continues until no swaps are made or the comparison limit is reached. The inner loop compares adjacent elements. The condition checks if the element at index `i` has a smaller `BorrowCount` than at index `i+1` (for descending order), OR if they are equal, it compares their `Title` values alphabetically to see if they need to be swapped (ascending order). If the swap conditions are met, a record-level swap is conducted using a temporary `Book` variable, and `Swapped` is set to `TRUE`.

Marking scheme

- 1.7 marks: Correct procedure header.
- 2 marks: Nested bubble sort loops implemented correctly.
- 3 marks: Complex compound `IF` condition evaluating both `BorrowCount` (descending) and `Title` (ascending).
- 2 marks: Swap operation using a temporary variable of record type `Book`.
- 2 marks: Correct optimization tracking (reducing comparison limit and tracking swap boolean).
Question 7 · Pseudocode Construction & Tracing
10.7 marks
An identifier is valid if it starts with a lowercase letter (`'a'`-`'z'`), followed by zero or more characters that are either lowercase letters or digits (`'0'`-`'9'`), and terminates with a single full stop (`'.'`).

The function `ReadChar() RETURNS CHARACTER` returns the next character from an input buffer.

Write pseudocode for a state-machine function `ValidateIdentifier() RETURNS BOOLEAN` to check if the stream of characters forms a valid identifier. Use four states:
- `"START"` (the initial state)
- `"VALID_CHARS"` (when processing valid alphanumeric characters)
- `"END_STATE"` (when a terminal full stop is found)
- `"ERROR"` (when an unexpected character or transition occurs)

The loop must terminate when the state is either `"END_STATE"` or `"ERROR"`. The function must return `TRUE` if the state machine terminates in the `"END_STATE"` and `FALSE` otherwise.
Show answer & marking scheme

Worked solution

The function uses a state variable `CurrentState` initialized to `"START"`. It enters a `WHILE` loop which continues as long as we are not in `"END_STATE"` or `"ERROR"`. Inside the loop, it reads a character. In the `"START"` state, it checks if the character is a lowercase letter; if so, it moves to `"VALID_CHARS"`, otherwise it flags an `"ERROR"`. In the `"VALID_CHARS"` state, if the character is alphanumeric, it remains in `"VALID_CHARS"`. If it is a dot `'.'`, it transitions to `"END_STATE"`. Any other input character leads to `"ERROR"`. Once the loop terminates, the function returns `TRUE` only if the final state is `"END_STATE"`.

Marking scheme

- 1.7 marks: Correct function header, declarations, and return statement.
- 2 marks: Loop control structure that terminates correctly on `"END_STATE"` or `"ERROR"`.
- 2 marks: State transition logic for `"START"` checking for lowercase letter.
- 3 marks: State transition logic for `"VALID_CHARS"` checking for alphanumeric characters and terminating dot.
- 2 marks: Return value based on final state check.

Paper 3 Advanced Theory

Answer all advanced theory questions. Use mathematical steps where required for K-maps and Float normalization.
13 Question · 74.10000000000002 marks
Question 1 · Analytical & Mathematical Computer Science
5.7 marks
A computer system represents floating-point numbers using a 12-bit format: an 8-bit mantissa and a 4-bit exponent, both stored in two's complement. Convert the denary value \(-7.375\) into this normalized floating-point format. Show all working, including how you achieved normalization, and write down the final mantissa and exponent.
Show answer & marking scheme

Worked solution

1) Express the absolute value \(7.375\) in binary: \(7 = 0111_2\) and \(0.375 = 0.011_2\), so \(7.375 = 0111.011_2\).
2) Find the two's complement of \(7.375\) to represent \(-7.375\): Invert the bits of \(0111.0110\) to get \(1000.1001\) and add 1, yielding \(1000.1010_2\) (which equals \(-8 + 0.5 + 0.125 = -7.375\)).
3) Normalize the binary value: A normalized negative floating-point number must start with the bits 1.0. Shift the binary point 3 places to the left to get \(1.0001010_2\).
4) Determine the exponent: Since the binary point was shifted 3 places to the left, the exponent is \(+3\).
5) Write the final representation:
- Mantissa (8 bits): \(10001010\)
- Exponent (4 bits in two's complement for \(+3\)): \(0011\).

Marking scheme

1 mark for correct binary representation of absolute denary value (\(7.375 = 0111.011_2\)).
1 mark for correct two's complement representation of \(-7.375\) (\(1000.101_2\)).
1.7 marks for explaining the normalization step (shifting binary point 3 places left to start with '1.0').
1 mark for the correct 8-bit mantissa (\(10001010\)).
1 mark for the correct 4-bit exponent (\(0011\)).
Question 2 · Analytical & Mathematical Computer Science
5.7 marks
Using Karnaugh Maps (K-maps) or Boolean algebraic laws, simplify the following Boolean expression to its minimum Sum-of-Products (SoP) form: \(X = A\cdot\bar{B}\cdot\bar{C} + \bar{A}\cdot\bar{B}\cdot C + A\cdot B\cdot C + A\cdot\bar{B}\cdot C + \bar{A}\cdot\bar{B}\cdot\bar{C}\). Show your simplification steps.
Show answer & marking scheme

Worked solution

Method 1: Using a Karnaugh Map.
We place 1s in the cells corresponding to the terms:
- \(A\cdot\bar{B}\cdot\bar{C} \rightarrow (1,0,0)\)
- \(\bar{A}\cdot\bar{B}\cdot C \rightarrow (0,0,1)\)
- \(A\cdot B\cdot C \rightarrow (1,1,1)\)
- \(A\cdot\bar{B}\cdot C \rightarrow (1,0,1)\)
- \(\bar{A}\cdot\bar{B}\cdot\bar{C} \rightarrow (0,0,0)\)

Grouping adjacent cells:
- A group of 4 (quad) of cells \((0,0,0), (0,0,1), (1,0,0), (1,0,1)\) simplifies to \(\bar{B}\).
- A group of 2 (pair) of cells \((1,0,1), (1,1,1)\) simplifies to \(A\cdot C\).
Summing these products yields the minimum expression: \(X = \bar{B} + A\cdot C\).

Method 2: Using Boolean laws.
\(X = \bar{B}\cdot\bar{C}(A + \bar{A}) + \bar{B}\cdot C(A + \bar{A}) + A\cdot B\cdot C\)
\(X = \bar{B}\cdot\bar{C} + \bar{B}\cdot C + A\cdot B\cdot C\)
\(X = \bar{B}(\bar{C} + C) + A\cdot B\cdot C\)
\(X = \bar{B} + A\cdot B\cdot C\)
Applying the distributive law: \(X = (\bar{B} + A\cdot B)(\bar{B} + C) = (\bar{B} + A)(\bar{B} + B)(\bar{B} + C) = (\bar{B} + A)(\bar{B} + C) = \bar{B} + A\cdot C\).

Marking scheme

1.7 marks for plotting correct 1s on K-map or setting up algebraic groupings.
2 marks for identifying the 4-cell group (or proving the algebraic elimination of \(C\) and \(A\) to leave \(\bar{B}\)).
2 marks for identifying the 2-cell group (or proving the algebraic reduction to \(A\cdot C\)).
Question 3 · Analytical & Mathematical Computer Science
5.7 marks
a) Convert the following infix expression to Reverse Polish Notation (RPN): \((P + Q) * (R - S / T)\).
b) Evaluate the following RPN expression using a stack: `8 4 2 / * 3 +`. Show the trace of the stack at each step and state the final evaluated value.
Show answer & marking scheme

Worked solution

a) Conversion of \((P + Q) * (R - S / T)\):
- First evaluate inner brackets: \((P + Q)\) becomes `P Q +`.
- Within the second bracket, division has higher precedence: \(S / T\) becomes `S T /`.
- Then subtraction: \(R - S/T\) becomes `R S T / -`.
- Finally, multiply the two bracket terms: `P Q + R S T / - *`.

b) Stack trace for `8 4 2 / * 3 +`:
- Push 8: Stack \([8]\)
- Push 4: Stack \([8, 4]\)
- Push 2: Stack \([8, 4, 2]\)
- Operator `/`: Pop 2 and 4. Evaluate \(4 / 2 = 2\). Push 2. Stack \([8, 2]\)
- Operator `*`: Pop 2 and 8. Evaluate \(8 * 2 = 16\). Push 16. Stack \([16]\)
- Push 3: Stack \([16, 3]\)
- Operator `+`: Pop 3 and 16. Evaluate \(16 + 3 = 19\). Push 19. Stack \([19]\).
Final value is 19.

Marking scheme

2 marks for the correct RPN conversion: `P Q + R S T / - *` (1 mark for partial progress).
2 marks for showing a complete, correct stack trace step-by-step.
1.7 marks for the correct final evaluated value of 19.
Question 4 · Analytical & Mathematical Computer Science
5.7 marks
A processor has an instruction execution pipeline consisting of 5 stages: Instruction Fetch (IF), Instruction Decode (ID), Operand Fetch (OF), Instruction Execute (EX), and Write Back (WB). Each stage takes exactly 1 clock cycle to complete.
Calculate how many clock cycles are saved when executing a block of 6 independent instructions on this pipelined processor compared to a non-pipelined processor. Show your calculations for both processors.
Show answer & marking scheme

Worked solution

1) Non-pipelined processor execution:
- Each instruction must complete all 5 stages before the next instruction begins.
- Time for 1 instruction = 5 clock cycles.
- Total time for 6 instructions = \(6 \times 5 = 30\) clock cycles.

2) Pipelined processor execution:
- In a pipelined processor, a new instruction can enter the pipeline at every clock cycle (assuming no hazards).
- The first instruction takes 5 clock cycles to complete.
- Each subsequent instruction completes on the next consecutive clock cycle.
- Total time for 6 instructions = \(5 \text{ (for the first)} + (6 - 1) \text{ (for the remaining 5)} = 10\) clock cycles.

3) Clock cycles saved:
- \(\text{Savings} = 30 - 10 = 20\) clock cycles.

Marking scheme

2 marks for calculating non-pipelined total clock cycles (30 cycles) with working.
2 marks for calculating pipelined total clock cycles (10 cycles) with working or pipeline diagram.
1.7 marks for calculating the correct final difference (20 cycles).
Question 5 · Analytical & Mathematical Computer Science
5.7 marks
In an RSA cryptography key-generation setup, a user chooses two prime numbers: \(p = 3\) and \(q = 11\).
a) Calculate the public modulus \(n\) and Totient function \(\phi(n)\).
b) Given that the public exponent \(e = 3\), verify mathematically that the private key exponent \(d\) is \(7\).
c) Encrypt the integer message \(M = 5\) using the public key \((e, n)\).
Show answer & marking scheme

Worked solution

a) Public modulus \(n = p \times q = 3 \times 11 = 33\).
Totient function \(\phi(n) = (p - 1)(q - 1) = 2 \times 10 = 20\).

b) The private exponent \(d\) must satisfy the relation \((d \times e) \equiv 1 \pmod{\phi(n)}\).
Substitute \(e = 3\) and \(\phi(n) = 20\):
\((d \times 3) \equiv 1 \pmod{20}\).
Testing \(d = 7\):
\(7 \times 3 = 21\).
Since \(21 = 1 \times 20 + 1\), we have \(21 \equiv 1 \pmod{20}\). Therefore, \(d = 7\) is verified.

c) Ciphertext \(C\) is computed as: \(C \equiv M^e \pmod{n}\).
Substitute \(M = 5, e = 3, n = 33\):
\(C \equiv 5^3 \pmod{33}\)
\(5^3 = 125\).
Divide 125 by 33: \(125 \div 33 = 3\) remainder \(26\) (since \(33 \times 3 = 99\) and \(125 - 99 = 26\)).
So, \(C = 26\).

Marking scheme

1 mark for calculating \(n = 33\).
1 mark for calculating \(\phi(n) = 20\).
1.7 marks for demonstrating the modular equation \((7 \times 3) \equiv 1 \pmod{20}\) to verify \(d\).
2 marks for calculating the correct encrypted ciphertext \(C = 26\) with step-by-step modular arithmetic.
Question 6 · Analytical & Mathematical Computer Science
5.7 marks
A Deterministic Finite Automaton (DFA) recognizes strings defined by the regular expression: `a(b|c)*d`.
Define the state transitions for the states:
- \(S_0\): Start state
- \(S_1\): Intermediary state after reading 'a'
- \(S_2\): Accepting/final state
- \(S_e\): Sink/error state

Describe the state transition table by listing all target states from \(S_0\) and \(S_1\) for inputs `a`, `b`, `c`, and `d`.
Show answer & marking scheme

Worked solution

To construct the DFA for the regular expression `a(b|c)*d`:
1) From \(S_0\) (start state):
- Must read 'a' to begin a valid string. Transition: `a` \(\rightarrow S_1\).
- Reading `b`, `c`, or `d` first is invalid. Transition: `b, c, d` \(\rightarrow S_e\).

2) From \(S_1\) (after reading 'a'):
- Can read any number of 'b' or 'c' characters. Transition: `b` \(\rightarrow S_1\), `c` \(\rightarrow S_1\).
- Reading 'd' successfully completes the pattern. Transition: `d` \(\rightarrow S_2\) (accepting state).
- Reading another 'a' is invalid. Transition: `a` \(\rightarrow S_e\).

3) From \(S_2\) (accepting state):
- Any further input makes the string invalid since the pattern must end with 'd'. Transition: `a, b, c, d` \(\rightarrow S_e\).

4) From \(S_e\) (sink state):
- Remains in \(S_e\) for all inputs: `a, b, c, d` \(\rightarrow S_e\).

Marking scheme

1.7 marks for identifying the correct transitions from \(S_0\) (\(a \rightarrow S_1\), other inputs \(\rightarrow S_e\)).
2 marks for identifying the correct transitions from \(S_1\) (\(b, c \rightarrow S_1\), \(d \rightarrow S_2\)).
1 mark for setting invalid transitions from \(S_1\) to \(S_e\).
1 mark for clearly stating that \(S_2\) is the only accepting state.
Question 7 · Analytical & Mathematical Computer Science
5.7 marks
A programming language syntax is defined by the following Backus-Naur Form (BNF) rules:
` ::= 0 | 1 | 2 | 3`
` ::= X | Y`
` ::= | `

Determine whether each of the following three strings is valid or invalid according to these BNF rules. Provide a step-by-step syntactic derivation or justification for each:
1) `X01`
2) `0Y`
3) `Y`
Show answer & marking scheme

Worked solution

1) String `X01`:
- Step 1: `X` is a `` (Rule 2).
- Step 2: Since `X` is a ``, it is also a `` (Rule 3: ` ::= `).
- Step 3: `0` is a `` (Rule 1). Under ` ::= `, the combination of `` (`X`) and `` (`0`) forms a new `` (`X0`).
- Step 4: `1` is a `` (Rule 1). Using ` ::= ` again, the `` (`X0`) followed by `` (`1`) forms the `` `X01`.
- Result: Valid.

2) String `0Y`:
- According to the rules, a `` must start with a `` (since the recursive base case is ``).
- The string starts with `0` which is a ``. There is no rule where a `` can start with a ``.
- Result: Invalid.

3) String `Y`:
- `Y` is a `` (Rule 2).
- Under ` ::= `, `Y` is directly a ``.
- Result: Valid.

Marking scheme

2 marks for explaining and proving that `X01` is valid using recursive derivation steps.
2 marks for explaining why `0Y` is invalid (violates the base case requirement of starting with a ``).
1.7 marks for identifying and explaining that `Y` is valid directly from the base rule.
Question 8 · Analytical & Mathematical Computer Science
5.7 marks
Analyze the following algorithm and determine its time complexity in Big O notation. Show your mathematical derivation step-by-step:

```
FUNCTION process(n)
DECLARE total : INTEGER
total <- 0
FOR i <- 1 TO n
j <- 1
WHILE j < n
total <- total + 1
j <- j * 2
ENDWHILE
ENDFOR
RETURN total
ENDFUNCTION
```
Show answer & marking scheme

Worked solution

1) Outer loop analysis:
- The outer loop `FOR i <- 1 TO n` executes exactly \(n\) times.

2) Inner loop analysis:
- In the inner loop, `j` starts at 1 and is multiplied by 2 in each iteration (`j <- j * 2`).
- The loop continues as long as `j < n`.
- The values of `j` over iterations are: \(1, 2, 4, 8, ..., 2^k\).
- The loop terminates when \(2^k \ge n\), which implies \(k \approx \log_2(n)\) iterations.
- Thus, the inner loop executes \(O(\log n)\) times for each iteration of the outer loop.

3) Total complexity:
- Total iterations = (outer loop iterations) \(\times\) (inner loop iterations)
- Total complexity = \(n \times \log_2(n) = O(n \log n)\).

Marking scheme

2 marks for identifying that the outer loop executes \(n\) times (\(O(n)\)).
2 marks for explaining that the inner loop doubles the control variable `j` each time, leading to logarithmic complexity (\(O(\log n)\)).
1.7 marks for mathematically combining both loops to arrive at the final time complexity of \(O(n \log n)\).
Question 9 · Analytical & Mathematical Computer Science
5.7 marks
A 12-bit floating-point system uses a 2's complement representation for both the mantissa and the exponent. The mantissa is represented by 8 bits (including 1 sign bit). The exponent is represented by 4 bits (including 1 sign bit). Convert the denary value \(-3.25\) into this normalized 12-bit floating-point format. Show all your working steps clearly.
Show answer & marking scheme

Worked solution

Step 1: Convert the absolute value \(3.25\) to fixed-point binary. \(3.25_{10} = 11.01_2\).
Step 2: Express \(-3.25\) in 8-bit two's complement fixed-point form. Represent \(+3.25\) in 8 bits as `0011.0100`. Invert the bits to get `1100.1011`, and add 1 to the least significant bit to get `1100.1100` (which corresponds to \(-8 + 4 + 0.5 + 0.25 = -3.25\)).
Step 3: Normalize the value. A negative normalized floating-point number must start with `10`. To change the mantissa from `1100.1100` to a normalized format starting with `1.0`, shift the binary point to the left to obtain `1.0011000`.
Step 4: Determine the exponent. The normalized mantissa `10011000` represents the denary value \(-1 + 0.125 + 0.0625 = -0.8125\). To restore the original value of \(-3.25\), we solve \(-0.8125 \times 2^x = -3.25\), giving \(2^x = 4\), so \(x = 2\).
Step 5: Represent the exponent in 4-bit 2's complement: \(+2\) is `0010`.
Step 6: Combine the mantissa and exponent: `10011000 0010`.

Marking scheme

1 mark for converting the absolute value to binary (\(11.01\)).
1.7 marks for correctly converting the negative number to two's complement form.
1.5 marks for shifting the mantissa to begin with `10` (normalization).
1.5 marks for calculating the exponent as \(+2\) (or binary `0010`) and combining to get the final correct 12-bit sequence.
Question 10 · Analytical & Mathematical Computer Science
5.7 marks
A digital logic circuit is described by the Boolean expression: \(F(A, B, C, D) = \sum(0, 2, 5, 7, 8, 10, 13, 15)\). Using a 4-variable Karnaugh Map (K-map), simplify this expression to its minimum sum-of-products (SOP) form. Show the grouping of terms on the K-map and state the final simplified Boolean expression.
Show answer & marking scheme

Worked solution

Step 1: Construct a 4-variable K-map with row headers \(AB\) (00, 01, 11, 10) and column headers \(CD\) (00, 01, 11, 10).
Step 2: Place 1s in the cells corresponding to the minterms: \(0\) (0000), \(2\) (0010), \(5\) (0101), \(7\) (0111), \(8\) (1000), \(10\) (1010), \(13\) (1101), and \(15\) (1111).
Step 3: Group the 1s into the largest possible powers-of-two blocks:
- Group 1 (Corner group of 4): The four corners corresponding to cells 0, 2, 8, and 10. These cells represent \(\bar{A}\bar{B}\bar{C}\bar{D}\), \(\bar{A}\bar{B}C\bar{D}\), \(A\bar{B}\bar{C}\bar{D}\), and \(A\bar{B}C\bar{D}\). The variable \(A\) changes state and is eliminated; the variable \(C\) changes state and is eliminated. This leaves the simplified term \(\bar{B}\bar{D}\).
- Group 2 (Center group of 4): The 2x2 block corresponding to cells 5, 7, 13, and 15. These cells represent \(\bar{A}B\bar{C}D\), \(\bar{A}BCD\), \(AB\bar{C}D\), and \(ABCD\). The variable \(A\) changes state and is eliminated; the variable \(C\) changes state and is eliminated. This leaves the simplified term \(BD\).
Step 4: Combine the simplified terms: \(F = \bar{B}\bar{D} + BD\) (which is also equivalent to \(B \odot D\)).

Marking scheme

2 marks for drawing/describing a correct K-map layout with 1s in the appropriate cells.
1.7 marks for correctly grouping the four corners and simplifying to \(\bar{B}\bar{D}\).
1.5 marks for correctly grouping the center 2x2 block and simplifying to \(BD\).
0.5 marks for writing the final combined SOP expression.
Question 11 · Analytical & Mathematical Computer Science
5.7 marks
Alice wishes to securely send a sensitive document to Bob. The system must guarantee data confidentiality, integrity, and non-repudiation. Describe the step-by-step cryptographic protocol using asymmetric encryption and digital signatures to achieve this. Explicitly identify which keys (Alice's public key, Alice's private key, Bob's public key, Bob's private key) are used at each stage by both the sender and receiver.
Show answer & marking scheme

Worked solution

To achieve all three security goals, the following process is executed:
1. **Hash Generation**: Alice passes the document through a cryptographic hash function (e.g., SHA-256) to produce a fixed-size message digest. This ensures integrity.
2. **Digital Signature Creation**: Alice encrypts the message digest using **Alice's private key**. This creates the digital signature and ensures non-repudiation.
3. **Confidentiality Encryption**: Alice encrypts both the original document and the digital signature using **Bob's public key** to produce the ciphertext. This ensures confidentiality.
4. **Transmission**: Alice sends the ciphertext to Bob.
5. **Decryption**: Bob receives the ciphertext and decrypts it using **Bob's private key** to retrieve the plaintext document and the digital signature.
6. **Signature Verification**: Bob decrypts the digital signature using **Alice's public key** to recover the original message digest. Bob then hashes the decrypted document using the same hash function and compares his calculated digest with the recovered digest. If they match, integrity and authenticity are verified.

Marking scheme

1.7 marks for identifying that the digital signature is created by encrypting the digest with Alice's private key.
1.5 marks for identifying that confidentiality is achieved by encrypting the message and signature with Bob's public key.
1.5 marks for identifying that Bob decrypts the outer package with his private key.
1 mark for identifying that Bob decrypts the signature using Alice's public key to verify identity.
Question 12 · Analytical & Mathematical Computer Science
5.7 marks
A RISC processor uses a 5-stage instruction pipeline: Instruction Fetch (IF), Instruction Decode (ID), Execute (EX), Memory Access (MEM), and Write Back (WB). Consider the execution of the following three assembly instructions:
1. `ADD R1, R2, R3` (writes to R1)
2. `SUB R4, R1, R5` (reads from R1)
3. `AND R6, R7, R8`

Assume that register writes happen in the first half of a clock cycle and register reads happen in the second half. Calculate the total number of clock cycles required to execute these three instructions:
(a) Without operand forwarding (stalls must be inserted to resolve data hazards).
(b) With operand forwarding (the result of the EX stage can be directly routed to the next EX stage).
Show answer & marking scheme

Worked solution

(a) Without operand forwarding:
- Instruction 1 (ADD) proceeds normally: IF (C1), ID (C2), EX (C3), MEM (C4), WB (C5). R1 is updated in the first half of cycle 5.
- Instruction 2 (SUB) has a data dependency on R1. It is fetched in C2, but must stall in the ID stage during C3 and C4 because the value of R1 is not yet written. In C5, it can decode and read R1 in the second half of the cycle. It then completes: EX (C6), MEM (C7), WB (C8).
- Instruction 3 (AND) is fetched in C5 (due to the pipeline stall), decoded in C6, executed in C7, MEM in C8, and WB in C9.
- Total: 9 clock cycles.

(b) With operand forwarding:
- Instruction 1 (ADD) proceeds: IF (C1), ID (C2), EX (C3), MEM (C4), WB (C5).
- Instruction 2 (SUB) is fetched in C2 and decoded in C3. The operand forwarding hardware routes the result of ADD from the EX/MEM register directly into the EX stage of SUB in cycle 4. Thus, SUB proceeds: EX (C4), MEM (C5), WB (C6).
- Instruction 3 (AND) proceeds: IF (C3), ID (C4), EX (C5), MEM (C6), WB (C7).
- Total: 7 clock cycles.

Marking scheme

2.85 marks for part (a): 1.85 marks for explaining the stalls during cycle 3 and 4, and 1 mark for stating the correct total of 9 cycles.
2.85 marks for part (b): 1.85 marks for explaining how forwarding bypasses the stall, and 1 mark for stating the correct total of 7 cycles.
Question 13 · Analytical & Mathematical Computer Science
5.7 marks
In a packet-switched network, a router uses Dijkstra's link-state routing algorithm to find the shortest paths from Node A to all other nodes. The network has 5 nodes (A, B, C, D, E) connected by the following bidirectional links with their respective transmission costs:
- A to B: cost 3
- A to C: cost 1
- B to C: cost 1
- B to D: cost 5
- C to D: cost 2
- C to E: cost 7
- D to E: cost 1

Trace the algorithm's execution step-by-step to find the shortest path and minimum transmission cost from Node A to Node E. Show the order of visited nodes and the final path.
Show answer & marking scheme

Worked solution

Step 1: Initialize distances from A:
Distances: [A: 0, B: inf, C: inf, D: inf, E: inf], Unvisited: {A, B, C, D, E}

Step 2: Visit A (cost 0):
- Neighbors of A: B (3), C (1).
- Update tentative distances: B = 3, C = 1.
- Visited: {A}

Step 3: Select closest unvisited node, C (cost 1):
- Neighbors of C: B (cost 1), D (cost 2), E (cost 7).
- Update tentative distances:
* B: min(3, 1+1) = 2 (via C)
* D: min(inf, 1+2) = 3 (via C)
* E: min(inf, 1+7) = 8 (via C)
- Visited: {A, C}

Step 4: Select closest unvisited node, B (cost 2):
- Neighbors of B: D (cost 5).
- Update tentative distances:
* D: min(3, 2+5) = 3 (no change)
- Visited: {A, C, B}

Step 5: Select closest unvisited node, D (cost 3):
- Neighbors of D: E (cost 1).
- Update tentative distances:
* E: min(8, 3+1) = 4 (via D)
- Visited: {A, C, B, D}

Step 6: Select closest unvisited node, E (cost 4). All nodes visited.

Final Shortest Path to E: A -> C -> D -> E with a total minimum cost of 4.

Marking scheme

1.7 marks for correct initialization and state after visiting Node A.
1.5 marks for showing the updated path to B and D after visiting Node C.
1.5 marks for showing the updated path to E after visiting Node D.
1.0 mark for stating the correct final path (A -> C -> D -> E) and cost (4).

Paper 4 Practical Programming

Answer all tasks. Save all programming solutions in the evidence file exactly as instructed. Program only in Java, Python or VB.
3 Question · 75 marks
Question 1 · Live Coding & Testing Evidence
25 marks
An outpatient clinic manages patients using a priority-based queue. Patients with a higher priority (indicated by a lower triage level number, where 1 is the highest priority and 5 is the lowest) are treated first. If patients have the same triage level, the patient who arrived first (indicated by a lower arrival sequence number) is treated first.

You are required to write program code to implement this priority queue using an array of objects.

**Task 1.1**
Create a class named `Patient`.
The class must have the following private attributes:
- `PatientName` (String)
- `TriageLevel` (Integer)
- `SequenceNumber` (Integer)

Define a constructor that initializes these attributes using parameters.
Define public getter methods for all three attributes: `GetName()`, `GetTriageLevel()`, and `GetSequence()`. Save this code in your evidence file.

**Task 1.2**
Create a class named `TriageQueue`.
The class must have the following private attributes:
- `Queue` (An array of 10 items of type `Patient` initialized to null/None)
- `Size` (Integer, initialized to 0)

Define a constructor that initializes `Size` to 0 and the array to hold up to 10 elements. Save this code in your evidence file.

**Task 1.3**
Write a method `Enqueue` within the `TriageQueue` class that takes a `Patient` object as a parameter.
The method must:
- Check if the queue is full (size is 10). If full, return `False`.
- Insert the patient into the array at the correct position based on priority:
- Higher priority (lower `TriageLevel` value) must be closer to index 0.
- If triage levels are equal, the patient with the lower `SequenceNumber` must be closer to index 0.
- Shift existing patients down to make room for the new patient.
- Increment `Size` and return `True`.
Save this code in your evidence file.

**Task 1.4**
Write a method `Dequeue` within the `TriageQueue` class.
The method must:
- Check if the queue is empty. If empty, return null/None.
- Retrieve the patient at index 0.
- Shift all remaining patients up by one position.
- Decrement `Size`.
- Return the retrieved patient.
Save this code in your evidence file.

**Task 1.5**
Write a main program that:
1. Instantiates a `TriageQueue` object.
2. Enqueues the following 5 patients in this order:
- "Alice", Triage Level: 3, Sequence Number: 1
- "Bob", Triage Level: 1, Sequence Number: 2
- "Charlie", Triage Level: 3, Sequence Number: 3
- "David", Triage Level: 2, Sequence Number: 4
- "Eva", Triage Level: 1, Sequence Number: 5
3. Calls `Dequeue` twice and outputs the name of each dequeued patient.
4. Iterates through the remaining elements in the queue and outputs their names and triage levels.
Run your program, take a screenshot of the output, and save it in your evidence file.
Show answer & marking scheme

Worked solution

A complete Python solution is provided containing both the class structure (`Patient`, `TriageQueue`) and standard array manipulations. Shifting operations safely move elements within bounds, inserting elements based on multi-key priority (TriageLevel, then SequenceNumber).

Marking scheme

- **Task 1.1**: (4 marks total)
- 1 mark: Class `Patient` defined with attributes private.
- 1 mark: Constructor with parameters matching specification.
- 2 marks: Implementation of three getter methods (`GetName()`, `GetTriageLevel()`, `GetSequence()`).

- **Task 1.2**: (3 marks total)
- 1 mark: Class `TriageQueue` defined with private attributes.
- 2 marks: Constructor initializing `Queue` array with 10 elements and `Size` to 0.

- **Task 1.3**: (8 marks total)
- 1 mark: `Enqueue` method signature and correct parameter.
- 1 mark: Guard condition checking if queue is full.
- 3 marks: Loop/logic finding correct insertion index based on priority (triage level comparison) and sequence number comparison.
- 2 marks: Correct shifting of subsequent elements downwards.
- 1 mark: Incrementing `Size` and returning success boolean.

- **Task 1.4**: (5 marks total)
- 1 mark: `Dequeue` checking if queue is empty.
- 1 mark: Correctly saving element at index 0.
- 2 marks: Shifting remaining items up one position.
- 1 mark: Decrementing `Size` and returning correct patient object.

- **Task 1.5**: (5 marks total)
- 1 mark: Queue instantiation.
- 1 mark: Correct insertion of 5 specified patients in order.
- 1 mark: Dequeuing and printing first two patients (Bob and Eva).
- 1 mark: Correctly listing remaining queue elements (David, Alice, Charlie).
- 1 mark: Program compiles, runs, and outputs correct sequence without crashes.
Question 2 · Live Coding & Testing Evidence
25 marks
A retail company uses a binary search tree (BST) to organize stock items based on alphabetical order of their stock codes. The BST is implemented using a static array of nodes to mimic a heap/pointers structure.

**Task 2.1**
Define a class `Node` with the following attributes:
- `StockCode` (String)
- `Quantity` (Integer)
- `LeftPointer` (Integer)
- `RightPointer` (Integer)

Define a constructor that initializes these attributes. Save this code in your evidence file.

**Task 2.2**
Write a program containing global variables:
- `Tree`: an array of 20 elements of type `Node`
- `RootPointer` (Integer)
- `FreePointer` (Integer)

Write a procedure `InitializeTree()` that:
- Configures the array to form a free list link. For index 0 to 18, `LeftPointer` must point to the next index (`index + 1`). Node 19's `LeftPointer` must be set to -1.
- Set `RightPointer` to -1, `StockCode` to `""` (empty string), and `Quantity` to -1 for all nodes.
- Set `RootPointer` to -1.
- Set `FreePointer` to 0.
Save this code in your evidence file.

**Task 2.3**
Write a recursive function `InsertNode(CurrentPointer, NewNodePointer)` that inserts a node at `NewNodePointer` into the binary search tree starting from `CurrentPointer` index.

The function must:
- Base case: If root is empty, this logic should be handled before or within the method. Assuming `CurrentPointer` is the index to compare:
- If `StockCode` of the new node is less than current node's `StockCode`:
- If `LeftPointer` is -1, set `LeftPointer` of current node to `NewNodePointer`.
- Otherwise, recursively call `InsertNode` on the left child index.
- If `StockCode` of the new node is greater than current node's `StockCode`:
- If `RightPointer` is -1, set `RightPointer` of current node to `NewNodePointer`.
- Otherwise, recursively call `InsertNode` on the right child index.
Save this code in your evidence file.

**Task 2.4**
Write a recursive procedure `InOrder(CurrentPointer)` that outputs the `StockCode` and `Quantity` of all items in alphabetical order. Save this code in your evidence file.

**Task 2.5**
Write main program code that:
1. Calls `InitializeTree()`.
2. Writes a helper procedure `AddStock(Code, Qty)` that takes a free node, updates its attributes, and calls `InsertNode` to place it in the BST. (Handles RootPointer update if BST was empty).
3. Inserts the following stock items in this sequence:
- "PROD50", quantity: 100
- "PROD20", quantity: 50
- "PROD80", quantity: 200
- "PROD30", quantity: 75
- "PROD10", quantity: 30
4. Runs an `InOrder` traversal starting from `RootPointer` and prints the output.
Run your program, take a screenshot of the output, and save it in your evidence file.
Show answer & marking scheme

Worked solution

The node tracking strategy links the free pointers correctly. Standard binary search insertion rules compare alphanumeric strings correctly. Recursive tree traversals execute in-order to display the products alphabetically.

Marking scheme

- **Task 2.1**: (3 marks total)
- 1 mark: `Node` class defined with four specified attributes.
- 2 marks: Constructor initializing attributes with specified values or parameters.

- **Task 2.2**: (5 marks total)
- 1 mark: Set array length to 20 and declared global pointers.
- 2 marks: Populated free list links where nodes 0-18 point left to `i + 1`, node 19 points left to -1.
- 1 mark: Initialized stock codes to empty and quantities/right pointers to -1.
- 1 mark: Set global variables `RootPointer` to -1 and `FreePointer` to 0.

- **Task 2.3**: (8 marks total)
- 1 mark: Subroutine definition of `InsertNode` taking current and new node index pointers.
- 2 marks: Correct condition branch determining if new node is less than current node stock code.
- 1 mark: Action when `LeftPointer` is -1 to set `LeftPointer` to `NewNodePointer`.
- 1 mark: Correct recursive call if `LeftPointer` is not -1.
- 2 marks: Handling right branching accurately when new node is greater than current node stock code.
- 1 mark: Recursion terminates properly with correct parameter propagation.

- **Task 2.4**: (5 marks total)
- 1 mark: `InOrder` procedure taking integer parameter for node index.
- 1 mark: Base case checking if pointer equals -1.
- 1 mark: Recursive call to left child.
- 1 mark: Output/print statement for stock data.
- 1 mark: Recursive call to right child.

- **Task 2.5**: (4 marks total)
- 1 mark: Correct configuration of `AddStock` to fetch free node index and advance `FreePointer`.
- 1 mark: Inserts all 5 items specified in the correct sequence.
- 1 mark: Calls `InOrder` with parameter `RootPointer`.
- 1 mark: Demonstration of output matching alphabetical listing: PROD10 (30), PROD20 (50), PROD30 (75), PROD50 (100), PROD80 (200).
Question 3 · Live Coding & Testing Evidence
25 marks
A drawing tool needs to implement a recursive region-filling (flood fill) algorithm on an 8x8 character grid. Connected cells containing the character `.` (empty space) are filled with `*` (fill character). Diagonal cells are not connected.

**Task 3.1**
Initialize a global 2D array named `Grid` of size 8 rows by 8 columns with characters.
Initialize the grid precisely as follows:
- Row 0: `["#", "#", "#", "#", "#", "#", "#", "#"]`
- Row 1: `["#", ".", ".", ".", "#", ".", ".", "#"]`
- Row 2: `["#", ".", "#", ".", "#", ".", "#", "#"]`
- Row 3: `["#", ".", "#", ".", ".", ".", ".", "#"]`
- Row 4: `["#", ".", "#", "#", "#", "#", ".", "#"]`
- Row 5: `["#", ".", ".", ".", ".", "#", ".", "#"]`
- Row 6: `["#", "#", "#", "#", ".", ".", ".", "#"]`
- Row 7: `["#", "#", "#", "#", "#", "#", "#", "#"]`

Write a procedure `DisplayGrid()` to cleanly output the grid to the console. Save this code in your evidence file.

**Task 3.2**
Write a recursive function `FloodFill(Row, Col, TargetChar, ReplacementChar)` that:
- Checks if `Row` or `Col` is outside the bounds of the 8x8 array. If it is out of bounds, return 0.
- Checks if the character at `Grid[Row][Col]` is different from `TargetChar`. If it is different, return 0.
- Replaces the character at `Grid[Row][Col]` with `ReplacementChar`.
- Recursively calls `FloodFill` on the 4 surrounding cardinal positions: up, down, left, right.
- Computes and returns the total count of cells filled during this invocation (which is 1 for the current cell plus the sum of returns from the 4 recursive calls).
Save this code in your evidence file.

**Task 3.3**
Write main program code that:
1. Outputs "Grid before fill:" and displays the initial grid status using `DisplayGrid()`.
2. Calls `FloodFill(1, 1, ".", "*")` to fill the starting pocket.
3. Outputs "Total cells filled: " followed by the returned value from the function.
4. Outputs "Grid after fill:" and prints the updated grid using `DisplayGrid()`.
Run your program, take a screenshot of the output, and save it in your evidence file.
Show answer & marking scheme

Worked solution

The recursive grid search utilizes a standard boundary and validation check for its base case. Cells that are visited have their value modified immediately to prevent infinite loops.

Marking scheme

- **Task 3.1**: (5 marks total)
- 2 marks: Correctly declared global array structure containing all 8 rows formatted as specified.
- 3 marks: Implementation of display procedure displaying row elements cleanly with loops.

- **Task 3.2**: (12 marks total)
- 2 marks: Parameterized function signature declaring Row, Col, TargetChar, ReplacementChar.
- 2 marks: Base case returning 0 for boundary errors (less than 0 or greater/equal to 8).
- 2 marks: Base case returning 0 when cell is not equal to `TargetChar`.
- 2 marks: Modifying the cell value correctly at coordinate (Row, Col) with replacement character.
- 2 marks: Executing recursive calls in all 4 Directions (Up, Down, Left, Right).
- 2 marks: Correct accumulation of count (1 + sum of four recursions) returned safely.

- **Task 3.3**: (8 marks total)
- 1 mark: Printing the grid state prior to fill.
- 2 marks: Calling `FloodFill(1, 1, ".", "*")`.
- 2 marks: Saving output and printing the correct cell modification count (the top-left connected compartment has exactly 11 fillable '.' cells).
- 2 marks: Printing correct final grid containing replacement characters.
- 1 mark: Clean non-infinite recursion termination.

Wondering how well you actually know this?

Thinka is an AI practice app for DSE students — unlimited questions, instant auto-marking, and detailed step-by-step solutions. 100,000+ students use it to confirm they actually know it, not just think they do.

Want more questions like this? Practice unlimited on Thinka — instant answers included.

Start Practising Free