AQA A-Level · PastPaper.sampleTitle

MetadataPastPaper.sampleTitle

Thinka Jun 2024 AQA A Level-Style Mock — Computer Science 7517

200 PastPaper.marks300 PastPaper.minutes2024
An original Thinka practice paper modelled on the structure and difficulty of the Jun 2024 AQA A Level Computer Science 7517 paper. Not affiliated with or reproduced from AQA.

Paper 1 Section A

Answer all theoretical, programmatic, and mathematical questions in the electronic answer document.
16 PastPaper.question · 37 PastPaper.marks
PastPaper.question 1 · Short Answer Theory
1.5 PastPaper.marks
Explain the distinction between passing a parameter by value and passing a parameter by reference, and state which method requires more memory space when passing large data structures.
PastPaper.showAnswers

PastPaper.workedSolution

1. Passing by value creates a separate copy of the parameter's data in memory for the subroutine. Passing by reference passes a pointer or memory address of the original data, so no copy of the actual data is made.
2. When passing large data structures, passing by value requires significantly more memory because a full copy of the large structure must be stored in the stack frame of the subroutine.

PastPaper.markingScheme

1 Mark: Correctly explaining that by value creates a local copy whereas by reference passes the memory address / pointer of the original data.
0.5 Marks: Identifying that passing by value requires more memory space for large data structures.
PastPaper.question 2 · Short Answer Theory
1.5 PastPaper.marks
Explain the difference between a static data structure and a dynamic data structure, and state one disadvantage of using a dynamic data structure.
PastPaper.showAnswers

PastPaper.workedSolution

1. A static data structure has a size that is fixed and defined when compiled; it cannot change during runtime. A dynamic data structure can expand or contract in size as items are added or removed during program execution.
2. A disadvantage of dynamic data structures is that they require additional memory overhead to store pointers/links to the next elements, and they may suffer from memory fragmentation or more complex memory management.

PastPaper.markingScheme

1 Mark: Clearly distinguishing between fixed size at compile-time (static) vs variable size during runtime (dynamic).
0.5 Marks: Any one valid disadvantage of dynamic structures (e.g., memory overhead from pointers, risk of memory fragmentation, lack of direct/index-based access leading to slower search, or risk of memory overflow if not managed correctly).
PastPaper.question 3 · Short Answer Theory
1.5 PastPaper.marks
State the purpose of the Domain Name System (DNS) and explain why a local DNS server might query an authoritative name server.
PastPaper.showAnswers

PastPaper.workedSolution

1. The primary purpose of the DNS is to translate user-friendly domain names (e.g., example.com) into machine-readable IP addresses.
2. A local DNS server acts as a recursive resolver. If it cannot find the mapping in its local cache, it traverses the hierarchy and eventually queries the authoritative name server, which holds the original, definitive DNS records for that domain, to obtain the correct, up-to-date IP address.

PastPaper.markingScheme

1 Mark: Correctly stating that DNS translates domain names into IP addresses.
0.5 Marks: Explaining that a query to an authoritative server is made to obtain the official, definitive record because it is not available or has expired in the local DNS server's cache.
PastPaper.question 4 · Short Answer Theory
1.5 PastPaper.marks
Describe the role of the Program Counter (PC) in the Fetch-Execute cycle and state how its value changes immediately after a fetch instruction.
PastPaper.showAnswers

PastPaper.workedSolution

1. The Program Counter (PC) is a dedicated register that stores the address of the next instruction to be fetched from main memory.
2. As soon as the current instruction is fetched from memory into the Instruction Register (or Memory Buffer Register), the PC is updated/incremented (usually by 1) so that it holds the address of the next sequential instruction.

PastPaper.markingScheme

1 Mark: Stating that the PC holds the address of the next instruction to be fetched.
0.5 Marks: Stating that its value is incremented / updated immediately after the fetch operation.
PastPaper.question 5 · Short Answer Theory
1.5 PastPaper.marks
Express the decimal number \(-18.375\) as a fixed-point binary representation using a 12-bit two's complement format, with 8 bits for the integer part (including sign bit) and 4 bits for the fractional part. Show your working.
PastPaper.showAnswers

PastPaper.workedSolution

1. Convert the positive value \(+18.375\) to binary:
- The integer part \(18 = 16 + 2 = 00010010_2\) (using 8 bits).
- The fractional part \(0.375 = 0.25 + 0.125 = 0110_2\) (using 4 bits).
- Thus, \(+18.375\) in binary is \(00010010.0110\).
2. Apply two's complement to get the negative value:
- Invert all bits of the 12-bit string: \(111011011001\).
- Add 1 to the least significant bit: \(111011011001 + 1 = 111011011010\).
- Therefore, the representation of \(-18.375\) is \(111011011010\).

PastPaper.markingScheme

1 Mark: Correct final 12-bit binary string: `111011011010` (accept with binary point as `11101101.1010`).
0.5 Marks: Showing correct working of converting positive 18.375 to binary (`00010010.0110`) or demonstrating the correct process of bit-inversion and adding 1.
PastPaper.question 6 · Short Answer Theory
1.5 PastPaper.marks
In functional programming, explain the concept of a 'higher-order function' and state which of the three standard functional operations—`map`, `filter`, or `fold` (reduce)—behaves differently by reducing a list to a single scalar value.
PastPaper.showAnswers

PastPaper.workedSolution

1. A higher-order function is defined by two characteristics (it must meet at least one): it accepts another function as an input parameter, or it returns a function as its output.
2. Among the three standard list operations, `map` applies a function to each element and returns a list of the same length; `filter` returns a subset of the list; and `fold` (or `reduce`) applies a combining function recursively across the list elements to accumulate them into a single final scalar value.

PastPaper.markingScheme

1 Mark: Clear definition of a higher-order function (takes function as argument AND/OR returns a function).
0.5 Marks: Correctly identifying `fold` (or `reduce`).
PastPaper.question 7 · Short Answer Theory
1.5 PastPaper.marks
Define what a regular language is in relation to formal languages, and state the type of abstract machine that is used to recognise any regular language.
PastPaper.showAnswers

PastPaper.workedSolution

1. In formal language theory, a regular language is a language that can be generated by a regular grammar, represented by a regular expression, or recognised by a finite state automaton.
2. The class of abstract machine that recognises any regular language is a Finite State Machine (FSM), which can be either a Deterministic Finite Automaton (DFA) or a Non-deterministic Finite Automaton (NFA).

PastPaper.markingScheme

1 Mark: Stating that a regular language is one that can be defined by a regular expression, regular grammar, or accepted/recognised by a finite state machine.
0.5 Marks: Stating Finite State Machine (FSM) / Finite State Automaton (FSA) (accept DFA or NFA).
PastPaper.question 8 · Short Answer Theory
1.5 PastPaper.marks
Simplify the Boolean expression \(\overline{A \cdot B} \cdot (A + B)\) using Boolean identities and De Morgan's laws. Show your steps.
PastPaper.showAnswers

PastPaper.workedSolution

1. Apply De Morgan's law to the term \(\overline{A \cdot B}\):
\(\overline{A \cdot B} = \overline{A} + \overline{B}\)
2. Substitute back and expand the expression using the distributive law:
\((\overline{A} + \overline{B}) \cdot (A + B) = \overline{A}\cdot A + \overline{A}\cdot B + \overline{B}\cdot A + \overline{B}\cdot B\)
3. Use the identity \(X \cdot \overline{X} = 0\):
\(\overline{A}\cdot A = 0\) and \(\overline{B}\cdot B = 0\)
4. This simplifies the expression to:
\(0 + \overline{A}\cdot B + A\cdot \overline{B} + 0 = \overline{A}\cdot B + A\cdot \overline{B}\) (which is the exclusive-OR operation, \(A \oplus B\)).

PastPaper.markingScheme

1 Mark: Correct final simplified expression, either \(\overline{A} \cdot B + A \cdot \overline{B}\) or \(A \oplus B\) (or equivalent plain text representation like `NOT A AND B OR A AND NOT B` or `A XOR B`).
0.5 Marks: Showing the correct intermediate step using De Morgan's Law to get \(\overline{A} + \overline{B}\) or expanding to \(\overline{A}A + \overline{A}B + A\overline{B} + \overline{B}B\).
PastPaper.question 9 · Short Answer Theory
1.5 PastPaper.marks
A circular queue is implemented in an array of size 6, with indices 0 to 5. Assume that Front points to the index of the first element in the queue, and Rear points to the index of the last element in the queue. Enqueueing increments Rear (wrapping around to 0 after 5) and writes the element. Dequeueing reads the element at Front and then increments Front (wrapping around to 0 after 5).

The queue initially contains three elements: ['A', 'B', 'C'] at indices 2, 3, and 4 respectively (Front = 2, Rear = 4).

State the value of Front and Rear after two enqueue operations (inserting 'D' and 'E') and one dequeue operation have been completed in sequence.
PastPaper.showAnswers

PastPaper.workedSolution

1. Initial state: Front = 2, Rear = 4.
2. Enqueue 'D': Rear increments to (4 + 1) % 6 = 5. Rear is now 5. 'D' is placed at index 5.
3. Enqueue 'E': Rear increments to (5 + 1) % 6 = 0. Rear is now 0. 'E' is placed at index 0.
4. Dequeue: Front increments to (2 + 1) % 6 = 3. Front is now 3 (element 'A' at index 2 is removed).

Final values: Front = 3, Rear = 0.

PastPaper.markingScheme

Award 1.5 marks for both values correct:
- Front = 3 (0.75 marks)
- Rear = 0 (0.75 marks)

Alternatively, if only one value is correct, award 0.75 marks.
PastPaper.question 10 · Short Answer Theory
1.5 PastPaper.marks
Explain, in the context of relational database normalisation, why a relation containing a transitive dependency is NOT in Third Normal Form (3NF).
PastPaper.showAnswers

PastPaper.workedSolution

Third Normal Form (3NF) requires a relation to be in Second Normal Form (2NF) and to have no transitive dependencies. A transitive dependency exists when a non-key attribute determines another non-key attribute (e.g., if A -> B and B -> C, then A -> C transitively). In 3NF, every non-key attribute must be dependent only on the primary key (the 'key, the whole key, and nothing but the key'). Having a transitive dependency means an attribute depends on another non-key attribute, violating this rule and causing data redundancy.

PastPaper.markingScheme

Award marks as follows:
- 1 mark: Correctly defining a transitive dependency (a non-key attribute functionally depending on another non-key attribute).
- 0.5 marks: Explaining how this violates 3NF requirements (3NF requires all non-key attributes to depend only on the primary key, or explaining that eliminating it prevents update/insertion/deletion anomalies).
PastPaper.question 11 · Short Answer Theory
1.5 PastPaper.marks
Write a regular expression that defines the language of all strings over the alphabet \(\Sigma = \{a, b\}\) that begin with 'a' and contain an even number of 'b's (including zero 'b's).
PastPaper.showAnswers

PastPaper.workedSolution

To match an even number of 'b's over the alphabet \(\{a, b\}\), the regular expression is `a*(ba*ba*)*`. Since the string must begin with 'a', we must prefix this pattern with at least one 'a'.

By ensuring the first character is 'a', we can write `a` followed by any sequence containing an even number of 'b's: `a(a*(ba*ba*)*)` which can also be written as `a+(ba*ba*)*` because the leading `a` followed by `a*` simplifies to `a+`.

PastPaper.markingScheme

Award marks as follows:
- 1.5 marks for any fully correct regular expression, such as `a(a*(ba*ba*)*)` or `a+(ba*ba*)*` (or equivalent).
- 0.75 marks for an expression that correctly handles even numbers of 'b's but fails to strictly enforce starting with 'a', or vice versa.
PastPaper.question 12 · Short Answer Theory
1.5 PastPaper.marks
Describe the fundamental difference between the Von Neumann architecture and the Harvard architecture in terms of how instructions and data are stored and accessed.
PastPaper.showAnswers

PastPaper.workedSolution

The stored program concept can be implemented in different ways:
1. Von Neumann Architecture: A unified memory space is shared by both programs (instructions) and data, accessed via a shared set of buses. This can lead to a bottleneck (the Von Neumann bottleneck) as instructions and data cannot be accessed simultaneously.
2. Harvard Architecture: Separate physical memory units and separate buses are used for instructions and data, allowing the processor to fetch instructions and read/write data at the same time.

PastPaper.markingScheme

- 1 mark: Stating that Von Neumann uses a single, shared physical memory and bus system for both instructions and data.
- 0.5 marks: Stating that Harvard uses separate physical memory spaces and separate buses for instructions and data.
PastPaper.question 13 · Trace Table Analysis
7 PastPaper.marks
An algorithm is represented by the following pseudocode. The array **A** is 0-indexed and contains the elements `[4, 4, 1, 1, 1, 6, 6]`.

```text
A ← [4, 4, 1, 1, 1, 6, 6]
N ← 7
Count ← 1
MaxCount ← 1
Val ← A[0]
I ← 1
WHILE I < N DO
IF A[I] = A[I-1] THEN
Count ← Count + 1
ELSE
IF Count > MaxCount THEN
MaxCount ← Count
Val ← A[I-1]
ENDIF
Count ← 1
ENDIF
I ← I + 1
ENDWHILE
IF Count > MaxCount THEN
MaxCount ← Count
Val ← A[N-1]
ENDIF
```

Complete the trace table below to show how the variables change during the execution of this algorithm. The first row, representing the initial state before the loop starts, has been completed for you. You should write a new value in the appropriate column only when a variable's value changes. You may not need to use all rows of the table.

| I | Count | MaxCount | Val |
| :---: | :---: | :---: | :---: |
| 1 | 1 | 1 | 4 |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
PastPaper.showAnswers

PastPaper.workedSolution

### Step-by-Step Execution Trace

1. **Initialisation**:
* `A` = `[4, 4, 1, 1, 1, 6, 6]` (Length `N` = 7)
* `Count` = 1, `MaxCount` = 1, `Val` = `A[0]` = 4, `I` = 1
* **Row 1**: `1 | 1 | 1 | 4` (given)

2. **Iteration 1** (`I = 1`):
* `A[1]` is 4, `A[0]` is 4. Since `A[1] = A[0]`, the `IF` condition is **True**.
* `Count` becomes 2.
* `I` is incremented to 2.
* **Row 2**: `I` becomes 2, `Count` becomes 2. Other variables do not change.

3. **Iteration 2** (`I = 2`):
* `A[2]` is 1, `A[1]` is 4. Since `A[2] != A[1]`, the `IF` condition is **False**.
* Nested condition: `Count > MaxCount` (2 > 1) is **True**.
* `MaxCount` becomes 2.
* `Val` is assigned `A[1]` which is 4 (no change in actual value).
* `Count` is reset to 1.
* `I` is incremented to 3.
* **Row 3**: `I` becomes 3, `Count` becomes 1, `MaxCount` becomes 2. (Note: writing 4 in `Val` is acceptable, but leaving it blank is standard as it didn't change from 4).

4. **Iteration 3** (`I = 3`):
* `A[3]` is 1, `A[2]` is 1. Since `A[3] = A[2]`, condition is **True**.
* `Count` becomes 2.
* `I` is incremented to 4.
* **Row 4**: `I` becomes 4, `Count` becomes 2.

5. **Iteration 4** (`I = 4`):
* `A[4]` is 1, `A[3]` is 1. Since `A[4] = A[3]`, condition is **True**.
* `Count` becomes 3.
* `I` is incremented to 5.
* **Row 5**: `I` becomes 5, `Count` becomes 3.

6. **Iteration 5** (`I = 5`):
* `A[5]` is 6, `A[4]` is 1. Since `A[5] != A[4]`, condition is **False**.
* Nested condition: `Count > MaxCount` (3 > 2) is **True**.
* `MaxCount` becomes 3.
* `Val` is assigned `A[4]` which is 1.
* `Count` is reset to 1.
* `I` is incremented to 6.
* **Row 6**: `I` becomes 6, `Count` becomes 1, `MaxCount` becomes 3, `Val` becomes 1.

7. **Iteration 6** (`I = 6`):
* `A[6]` is 6, `A[5]` is 6. Since `A[6] = A[5]`, condition is **True**.
* `Count` becomes 2.
* `I` is incremented to 7.
* **Row 7**: `I` becomes 7, `Count` becomes 2.

8. **Loop Termination** (`I = 7`):
* The loop condition `I < 7` is now **False**. Loop terminates.
* Post-loop check: `IF Count > MaxCount` (2 > 3) is **False**. No further changes.

### Completed Trace Table
| I | Count | MaxCount | Val |
|:---:|:---:|:---:|:---:|
| 1 | 1 | 1 | 4 |
| 2 | 2 | | |
| 3 | 1 | 2 | |
| 4 | 2 | | |
| 5 | 3 | | |
| 6 | 1 | 3 | 1 |
| 7 | 2 | | |

PastPaper.markingScheme

### Mark Distribution (Max 7 marks)

* **Mark 1 (I Column)**: Correct sequence of changes for `I` (2, 3, 4, 5, 6, 7 in order) down the rows.
* **Mark 2 (Count Column - Part 1)**: Correctly traces the first part of the `Count` sequence (updates to 2, then 1, then 2).
* **Mark 3 (Count Column - Part 2)**: Correctly traces the remaining sequence of `Count` (updates to 3, then 1, then 2).
* **Mark 4 (MaxCount Column)**: Correctly identifies both updates to `MaxCount` (changes to 2 at row 3, and to 3 at row 6).
* **Mark 5 (Val Column)**: Correctly identifies that `Val` updates to 1 at the correct step (row 6).
* **Mark 6 (Row Coordination)**: Correctly aligns all variable changes occurring within the same iteration on the same horizontal row (e.g., when `I` changes to 3, `Count` changes to 1, and `MaxCount` changes to 2).
* **Mark 7 (Final State)**: Correctly terminates the trace at `I = 7` with no further erroneous updates after the loop ends.

### Guidance Notes:
* Accept blank cells where values have not changed from the previous step.
* Accept the inclusion of explicit repeat values (e.g., writing `4` again for `Val` at Row 3) provided no values are incorrect.
PastPaper.question 14 · Algorithm Design Description
4 PastPaper.marks
A circular queue of capacity \(N\) is represented using an array `Queue` of size \(N\) (with indices \(0\) to \(N-1\)), and three integer variables:
* `front`: the index of the element at the front of the queue
* `rear`: the index of the element at the rear of the queue
* `count`: the current number of items in the queue

When the queue is empty, `front` is \(0\), `rear` is \(-1\), and `count` is \(0\).

Describe an algorithm, using pseudocode or structured English, to add (enqueue) an item `newItem` into this circular queue. Your algorithm must check for overflow and handle it by outputting an appropriate error message.
PastPaper.showAnswers

PastPaper.workedSolution

To add an element to a circular queue:
1. Check if the queue is full. This is done by checking if the current number of items `count` is equal to the capacity \(N\).
2. If it is full, output/return an error message and terminate.
3. Otherwise, update the `rear` index to the next position using circular increment: `rear = (rear + 1) MOD N`.
4. Store the `newItem` in the array at the new `rear` index: `Queue[rear] = newItem`.
5. Increment the `count` variable by 1.

PastPaper.markingScheme

1 mark: Check if the queue is full by comparing `count` with capacity \(N\).
1 mark: Handle full state appropriately by outputting an error message.
1 mark: Correctly update `rear` using modulo arithmetic (e.g. `(rear + 1) MOD N` or equivalent logic).
1 mark: Store `newItem` at the updated `rear` index in the `Queue` array and increment `count`.
PastPaper.question 15 · Algorithm Design Description
4 PastPaper.marks
A binary tree is implemented using an array of records named `Tree`. Each record has three fields: `LeftChild` (integer pointer to child index), `RightChild` (integer pointer to child index), and `Data` (string). An empty child is represented by the pointer value \(-1\).

Write a recursive algorithm, using pseudocode, for a function `CountLeaves(nodeIndex)` that returns the total number of leaf nodes (nodes with no children) in the subtree rooted at `nodeIndex`.

You should handle empty trees (where `nodeIndex` is \(-1\)) and leaf nodes correctly.
PastPaper.showAnswers

PastPaper.workedSolution

The function must count the leaf nodes recursively:
1. **Base Case 1**: If the current node pointer `nodeIndex` is \(-1\), the node is empty, so we return \(0\).
2. **Base Case 2**: If both `LeftChild` and `RightChild` are \(-1\), this node is a leaf, so we return \(1\).
3. **Recursive Step**: If the node is not a leaf, we return the sum of counting leaves in the left subtree and the right subtree: `CountLeaves(Tree[nodeIndex].LeftChild) + CountLeaves(Tree[nodeIndex].RightChild)`.

PastPaper.markingScheme

1 mark: Correct base case checking if `nodeIndex == -1` and returning 0.
1 mark: Correct base case identifying a leaf node (both `LeftChild` and `RightChild` are -1) and returning 1.
1 mark: Recursive step correctly calling `CountLeaves` on the left and right children.
1 mark: Summing the recursive calls and returning the result correctly.
PastPaper.question 16 · Algorithm Design Description
4 PastPaper.marks
Run-length encoding (RLE) is a simple form of data compression where consecutive identical characters are replaced by a single character and its frequency count. For example, the string `"AAABBC"` would be compressed to `"3A2B1C"`.

Write an algorithm, using pseudocode or structured English, for a function `CompressString(plainText)` that takes a non-empty string `plainText` as input and returns its run-length encoded version as a string.

You may assume that string concatenation is supported using the `+` operator, and characters in `plainText` can be accessed using zero-based indexing (e.g., `plainText[0]`, `plainText[1]`, etc.), with the length of the string given by `LEN(plainText)`.
PastPaper.showAnswers

PastPaper.workedSolution

To perform run-length encoding:
1. Initialize an empty string variable `compressed` and a counter `count` to 1.
2. Iterate through the string from index 0 to the second-to-last character (index `LEN(plainText) - 2`).
3. In each iteration, compare the current character `plainText[i]` with the next character `plainText[i + 1]`.
4. If they are equal, increment `count`.
5. If they are different, append the `count` (converted to string) and `plainText[i]` to `compressed`, and reset `count` to 1.
6. After the loop, append the final character group using the remaining `count` and the last character of the string.
7. Return the final `compressed` string.

PastPaper.markingScheme

1 mark: Correct initialization of results tracker (e.g. empty string) and the count variable to 1.
1 mark: Correct loop bounds iterating through the string without throwing out-of-bounds errors (comparing adjacent elements).
1 mark: Logic to increment count if characters match, and to append count + character and reset count to 1 if they differ.
1 mark: Handling the end of the string correctly (appending the final group after the loop) and returning the final compressed string.

Paper 1 Section B

Write a complete functional program from scratch matching the specification provided.
2 PastPaper.question · 13 PastPaper.marks
PastPaper.question 1 · practical
12 PastPaper.marks
Write a complete program in the programming language of your choice (or structured pseudocode) to calculate delivery costs for a batch of shipping packages.

The program must perform the following tasks:

1. Prompt the user to enter the number of packages to process. Validate this input to ensure it is an integer greater than or equal to 1. The program must repeatedly prompt the user until a valid integer is entered.

2. For each package, prompt for and read the following values (assume inputs for these are valid positive real numbers):
- The actual weight in kilograms (kg).
- Three dimensions: length, width, and height in centimeters (cm).

3. Calculate the volumetric weight using the formula:
$$\text{volumetric weight} = \frac{\text{length} \times \text{width} \times \text{height}}{5000}$$

4. Determine the chargeable weight, which is the greater of the actual weight and the volumetric weight.

5. Calculate the shipping cost for the package as follows:
- A base cost of £5.00.
- An additional charge of £1.50 per kg of the chargeable weight.
- If any of the three dimensions (length, width, or height) is strictly greater than 100 cm, apply an extra "oversize" surcharge of £10.00.

6. After processing all packages, calculate and output:
- The total shipping cost for the entire batch, formatted to 2 decimal places.
- The average actual weight of the packages processed.
- The total number of packages that incurred the oversize surcharge.
PastPaper.showAnswers

PastPaper.workedSolution

Here is an example solution written in Python:

```python
num_packages = 0
while num_packages < 1:
try:
num_packages = int(input("Enter number of packages: "))
if num_packages < 1:
print("Value must be 1 or greater.")
except ValueError:
print("Invalid input. Please enter an integer.")

total_cost = 0.0
total_weight = 0.0
oversize_count = 0

for i in range(num_packages):
print(f"
Package {i + 1}:")
weight = float(input("Enter weight (kg): "))
length = float(input("Enter length (cm): "))
width = float(input("Enter width (cm): "))
height = float(input("Enter height (cm): "))

volumetric_weight = (length * width * height) / 5000.0

if weight > volumetric_weight:
chargeable_weight = weight
else:
chargeable_weight = volumetric_weight

package_cost = 5.00 + (chargeable_weight * 1.50)

if length > 100 or width > 100 or height > 100:
package_cost += 10.00
oversize_count += 1

total_cost += package_cost
total_weight += weight

average_weight = total_weight / num_packages

print(f"
Total cost: £{total_cost:.2f}")
print(f"Average weight: {average_weight:.2f} kg")
print(f"Oversize packages: {oversize_count}")
```

PastPaper.markingScheme

Marks are awarded as follows:

1. **Validation loop**: Correct logic to prompt and validate that the entered number of packages is an integer greater than or equal to 1. (1 mark)
2. **Initialization**: Initialize cumulative variables (`total_cost`, `total_weight`, `oversize_count`) to 0 before the loop begins. (1 mark)
3. **Loop structure**: A loop that repeats exactly the number of times entered by the user. (1 mark)
4. **Inputs**: Correctly prompt and store four separate numeric variables (weight, length, width, height) inside the loop. (1 mark)
5. **Volumetric calculation**: Correctly calculate volumetric weight using the formula `(length * width * height) / 5000`. (1 mark)
6. **Chargeable weight selection**: Selection structure to determine the maximum of the actual weight and volumetric weight. (1 mark)
7. **Base + weight cost calculation**: Correctly calculate the base cost plus weight charge: `5.00 + (chargeable_weight * 1.50)`. (1 mark)
8. **Oversize check**: Selection structure that checks if length, width, OR height is strictly greater than 100. (1 mark)
9. **Oversize surcharge application**: Adding 10.00 to the package cost and incrementing the oversize package counter when the condition is met. (1 mark)
10. **Running totals**: Correctly accumulate package cost to `total_cost` and actual weight to `total_weight` within the loop. (1 mark)
11. **Average weight calculation**: Correct calculation of the average weight after the loop by dividing the accumulated weight by the number of packages. (1 mark)
12. **Formatted output**: Clear and correct output of all three final results, with the total cost formatted to 2 decimal places. (1 mark)
PastPaper.question 2 · Program Execution Evidence
1 PastPaper.marks
Write a Python function `CompressString(S)` that takes a string `S` of uppercase characters and returns a list of tuples representing its run-length encoding. For example, `CompressString("AAABBC")` must return `[("A", 3), ("B", 2), ("C", 1)]`.

Run your completed program with the input string `"HHHHTTTTTTSSSS"` and provide the exact output value returned by the function.

Write your answer exactly as a Python list of tuples, using standard single or double quotes for characters (e.g. `[('A', 3), ('B', 2)]`).
PastPaper.showAnswers

PastPaper.workedSolution

An example Python implementation of the function is as follows:

```python
def CompressString(S):
if not S:
return []

result = []
current_char = S[0]
count = 1

for char in S[1:]:
if char == current_char:
count += 1
else:
result.append((current_char, count))
current_char = char
count = 1

result.append((current_char, count))
return result
```

When `CompressString("HHHHTTTTTTSSSS")` is executed:
- 'H' occurs 4 times, yielding `('H', 4)`
- 'T' occurs 6 times, yielding `('T', 6)`
- 'S' occurs 4 times, yielding `('S', 4)`

Thus, the function returns `[('H', 4), ('T', 6), ('S', 4)]`.

PastPaper.markingScheme

1 mark: The exact list of tuples `[('H', 4), ('T', 6), ('S', 4)]` (allow double quotes instead of single quotes: `[("H", 4), ("T", 6), ("S", 4)]`).

Do not accept incorrect tuple pairings or incorrect counts.

Paper 1 Section C

Answer analytical questions concerning the provided skeleton code without making programming modifications.
9 PastPaper.question · 21.6 PastPaper.marks
PastPaper.question 1 · Code Analysis / Object-Oriented Theory
1.2 PastPaper.marks
Consider the following classes defined in a simulation:

```python
class GridItem:
def __init__(self, x, y):
self._x = x
self._y = y

class Obstacle(GridItem):
def __init__(self, x, y, damage):
super().__init__(x, y)
self._damage = damage
```

State the name of the object-oriented programming concept shown where class `Obstacle` is defined to acquire the attributes and methods of `GridItem`.
PastPaper.showAnswers

PastPaper.workedSolution

The syntax `class Obstacle(GridItem):` demonstrates inheritance. The subclass `Obstacle` inherits the coordinate fields `_x` and `_y` from its superclass `GridItem` and calls its constructor using `super().__init__(x, y)`.

PastPaper.markingScheme

1.2 marks: Awarded for 'Inheritance' or 'subclassing'. Reject 'Polymorphism' or 'Encapsulation'.
PastPaper.question 2 · Code Analysis / Object-Oriented Theory
1.2 PastPaper.marks
Consider the following `Drone` class design:

```python
class Drone(GridItem):
def __init__(self, x, y, max_battery):
super().__init__(x, y)
self._battery = max_battery
self._max_battery = max_battery

def get_battery(self):
return self._battery
```

Which object-oriented design principle is applied by prefixing `_battery` with an underscore and requiring external classes to call `get_battery()` to read its value?
PastPaper.showAnswers

PastPaper.workedSolution

This is encapsulation (information hiding). By keeping the internal representation (`_battery`) hidden or protected and exposing access through public methods (getters), class details are shielded from direct external modification.

PastPaper.markingScheme

1.2 marks: Awarded for 'Encapsulation' or 'Information hiding'.
PastPaper.question 3 · Code Analysis / Object-Oriented Theory
1.2 PastPaper.marks
A `Drone` instance is initialised with `Drone(x=2, y=3, max_battery=100)`. It has the following method:

```python
def move(self, dx, dy):
energy_cost = (abs(dx) + abs(dy)) * 5
if self._battery >= energy_cost:
self._x += dx
self._y += dy
self._battery -= energy_cost
return True
return False
```

If the drone executes the call `move(4, -2)`, calculate the remaining battery after the move.
PastPaper.showAnswers

PastPaper.workedSolution

1. The values are `dx = 4` and `dy = -2`.
2. The energy cost calculation is: `(abs(4) + abs(-2)) * 5 = (4 + 2) * 5 = 6 * 5 = 30`.
3. The current battery is `100`.
4. Since `100 >= 30`, the drone moves, and the new battery is `100 - 30 = 70`.

PastPaper.markingScheme

1.2 marks: Awarded for the correct final battery integer value of 70.
PastPaper.question 4 · Code Analysis / Object-Oriented Theory
1.2 PastPaper.marks
A drone's load system is implemented as follows:

```python
def load_cargo(self, item_weight):
if len(self._cargo) < 3:
self._cargo.append(item_weight)
return True
return False
```

If `self._cargo` currently contains three items `[1.5, 2.0, 1.2]`, state the boolean return value if `load_cargo(2.5)` is called.
PastPaper.showAnswers

PastPaper.workedSolution

The list length of `self._cargo` is 3. The condition `len(self._cargo) < 3` evaluates to `3 < 3`, which is `False`. Therefore, the block does not execute, and the method returns `False`.

PastPaper.markingScheme

1.2 marks: Awarded for 'False' (case-insensitive, but must indicate the boolean value false).
PastPaper.question 5 · Code Analysis / Object-Oriented Theory
1.2 PastPaper.marks
We wish to implement a subclass `HeavyDrone` that inherits from `Drone`. `HeavyDrone` overrides `load_cargo` to only allow items weighing less than 5.0 kg, whilst still enforcing the max limit of 3 items in total.

```python
class HeavyDrone(Drone):
def load_cargo(self, item_weight):
if item_weight < 5.0 and len(self._cargo) < 3:
self._cargo.append(item_weight)
return True
return False
```

Identify the conditional expression in the `if` statement that checks whether the size constraint of the inherited array list attribute `_cargo` is met.
PastPaper.showAnswers

PastPaper.workedSolution

The sub-expression checking the list capacity is `len(self._cargo) < 3`. This relies on the inherited protected list attribute `_cargo` from the base class `Drone`.

PastPaper.markingScheme

1.2 marks: Awarded for 'len(self._cargo) < 3' or equivalents such as checking length of cargo is less than 3.
PastPaper.question 6 · Code Analysis / Object-Oriented Theory
1.2 PastPaper.marks
When `HeavyDrone` defines its own custom implementation of the `load_cargo` method, replacing the standard implementation defined in its superclass `Drone`, what object-oriented programming term is used to describe this replacement?
PastPaper.showAnswers

PastPaper.workedSolution

This is method overriding (or simply overriding). It occurs when a subclass defines a method with the identical signature to a method in its superclass, replacing or expanding its behavior.

PastPaper.markingScheme

1.2 marks: Awarded for 'Method overriding' or 'overriding'. Reject 'method overloading'.
PastPaper.question 7 · Code Analysis / Object-Oriented Theory
1.2 PastPaper.marks
A class `Simulation` contains a collection of `GridItem` objects. If the `Simulation` object is destroyed, the `GridItem` objects still exist independently in memory because they were created outside the simulation context.

State the specific type of object-oriented association relationship that exists between `Simulation` and `GridItem`.
PastPaper.showAnswers

PastPaper.workedSolution

Since the lifetime of the child objects (`GridItem`) is independent of the parent container class (`Simulation`), this relationship is classified as aggregation (a 'has-a' relationship without ownership dependency).

PastPaper.markingScheme

1.2 marks: Awarded for 'Aggregation'. Reject 'Composition' (as composition implies lifetime dependency).
PastPaper.question 8 · Code Analysis / Object-Oriented Theory
1.2 PastPaper.marks
Suppose the private field `self._cargo` is stored using a standard dynamic array (such as a standard Python list). What is the average-case asymptotic time complexity, in Big O notation, of appending a single item to the cargo list?
PastPaper.showAnswers

PastPaper.workedSolution

Appending to the end of a dynamic array takes amortized constant time, which is expressed as \(O(1)\).

PastPaper.markingScheme

1.2 marks: Awarded for 'O(1)' or 'constant'.
PastPaper.question 9 · Analysis
12 PastPaper.marks
An incomplete class diagram and skeleton code representing a grid-based simulation game are shown below.

```python
class Position:
def __init__(self, x, y):
self._x = x
self._y = y
def get_coords(self):
return self._x, self._y

class Grid:
def __init__(self, width, height):
self._width = width
self._height = height
self._cells = [[None for _ in range(width)] for _ in range(height)]

def place_item(self, pos, item):
x, y = pos.get_coords()
if 0 <= x < self._width and 0 <= y < self._height:
self._cells[y][x] = item
return True
return False

class Actor:
def __init__(self, name, pos):
self._name = name
self._pos = pos

def move(self, dx, dy):
x, y = self._pos.get_coords()
self._pos = Position(x + dx, y + dy)

class Robot(Actor):
def __init__(self, name, pos, battery):
super().__init__(name, pos)
self.__battery = battery

def move(self, dx, dy):
if self.__battery >= 5:
super().move(dx, dy)
self.__battery -= 5
return True
return False
```

(a) Explain how polymorphism is demonstrated by the design of the `Actor` and `Robot` classes. [3 marks]

(b) Currently, there is no validation to prevent an actor from moving off the edge of the grid. Describe how the object-oriented design could be modified to validate and enforce boundary checks while adhering to the principle of encapsulation. Do not write code in your answer. [5 marks]

(c) Complete a dry run of the code by tracing the state of a `Robot` object initialized as follows:
`r = Robot(\"Cleaner\", Position(2, 3), 12)`

Trace the state variables of the `r` object after executing the following sequence of calls. State the final coordinate values of `r` and the final value of its private battery attribute. [4 marks]
1. `r.move(1, -1)`
2. `r.move(-2, 0)`
3. `r.move(0, 1)`
PastPaper.showAnswers

PastPaper.workedSolution

Part (a):
Polymorphism is demonstrated through method overriding. The subclass `Robot` overrides the `move` method inherited from its parent class `Actor`. When `move` is called on an instance of `Robot`, the overridden version is executed (which checks the battery and decrements it) instead of the default `move` method defined in `Actor`.

Part (b):
To maintain encapsulation and enforce boundaries:
1. The `Grid` class should encapsulate the responsibility of knowing the board dimensions and deciding whether a set of coordinates is valid (e.g., via an `is_valid_position(pos)` method).
2. The `Actor` (or `Robot`) class needs to hold a reference to the `Grid` object it belongs to (this can be passed to its constructor during instantiation).
3. Before updating the `_pos` attribute within the `move` method, the `Actor` should query the `Grid` object using the proposed new coordinates (e.g., `self._grid.is_valid_position(new_pos)`).
4. The coordinates are only updated if the grid confirms the destination is within bounds.

Part (c):
- Initial state: name = \"Cleaner\", position = (2, 3), battery = 12.
- Call 1: `r.move(1, -1)`. Battery (12 >= 5) is True. `super().move` updates position to (2+1, 3-1) = (3, 2). Battery decrements by 5 to 7. Returns True.
- Call 2: `r.move(-2, 0)`. Battery (7 >= 5) is True. `super().move` updates position to (3-2, 2+0) = (1, 2). Battery decrements by 5 to 2. Returns True.
- Call 3: `r.move(0, 1)`. Battery (2 >= 5) is False. The condition fails, so `super().move` is not called. Position remains (1, 2), and battery remains 2. Returns False.
- Final state: Position coords = (1, 2), Battery = 2.

PastPaper.markingScheme

Part (a) [Max 3 marks]:
- 1 mark: Identify that method overriding is being used.
- 1 mark: Identify that the `move` method is defined in `Actor` and redefined/overridden in `Robot`.
- 1 mark: Explain that calling `move` on a `Robot` object executes the subclass's version, illustrating polymorphic behavior.

Part (b) [Max 5 marks]:
- 1 mark: Suggest passing a reference of the `Grid` instance to the `Actor`/`Robot` constructor.
- 1 mark: Identify that `Grid` must provide a public validation method (e.g., `is_within_bounds(pos)`).
- 1 mark: Explain that this keeps boundary rules encapsulated within the `Grid` class (low coupling).
- 1 mark: Explain that the `move` method in `Actor` must calculate the temporary new position first.
- 1 mark: State that the coordinates `_pos` will only be updated if the validation check returns True.

Part (c) [Max 4 marks]:
- 1 mark: Correct state after Call 1 (coords = (3, 2), battery = 7).
- 1 mark: Correct state after Call 2 (coords = (1, 2), battery = 2).
- 1 mark: Correctly identify that Call 3 does not execute the move because battery (2) is less than 5.
- 1 mark: Correctly state final coordinates (1, 2) and final battery value 2.

Paper 1 Section D

Implement practical programmatic modifications and additions directly inside the skeleton program.
10 PastPaper.question · 39 PastPaper.marks
PastPaper.question 1 · Subclassing and Inheritance Mod
13 PastPaper.marks
An existing Skeleton Program for a text-based adventure game contains a base class called `Enemy`. Here is the definition of the `Enemy` class in Python:

```python
class Enemy:
def __init__(self, name, health, base_damage):
self._name = name
self._health = health
self._base_damage = base_damage

def take_damage(self, amount):
self._health -= amount
if self._health < 0:
self._health = 0

def get_damage(self):
return self._base_damage

def get_details(self):
return f"{self._name} - Health: {self._health}"
```

You are required to create a new class called `ShieldedEnemy` that inherits from the `Enemy` class.

A `ShieldedEnemy` has an additional integer attribute, `_shield_strength`, representing the current active shield capacity.

Write the complete Python code for the `ShieldedEnemy` class to implement the following specifications:
1. It must inherit from the `Enemy` class.
2. It must have a constructor (`__init__`) that accepts four parameters: `name`, `health`, `base_damage`, and `shield_strength`. It must call the parent constructor with appropriate arguments and initialize the custom `_shield_strength` attribute.
3. It must override the `take_damage` method. When a `ShieldedEnemy` takes damage:
* If the damage `amount` is less than or equal to the current `_shield_strength`, the shield absorbs all the damage. The `_shield_strength` is reduced by that amount.
* If the damage `amount` is greater than the current `_shield_strength`, the shield is reduced to 0. The remaining damage (damage amount minus the initial shield strength) must be deducted from the enemy's health (by calling the parent's `take_damage` method or modifying `_health` directly, ensuring health does not go below 0).
4. It must override the `get_damage` method. If `_shield_strength` is greater than 0, the enemy deals its base damage plus an additional bonus of 5 damage. Otherwise, it only deals its base damage.
5. It must override the `get_details` method to return the details of the enemy by invoking the parent class's `get_details` method and appending `" [Shield: X]"` (where X is the current shield strength) to the end.
PastPaper.showAnswers

PastPaper.workedSolution

To implement the requested features:
1. **Inheritance**: We declare `class ShieldedEnemy(Enemy):` to indicate that `ShieldedEnemy` is a subclass of `Enemy`.
2. **Constructor**: The constructor accepts four arguments: `name`, `health`, `base_damage`, and `shield_strength`. We use `super().__init__(name, health, base_damage)` to call the parent class's constructor, ensuring base parameters are initialized correctly. Then, we assign the `shield_strength` parameter to `self._shield_strength`.
3. **Overriding `take_damage`**: We first check if the incoming `amount` is less than or equal to `self._shield_strength`. If so, we just subtract `amount` from `self._shield_strength`. Otherwise, the remaining damage (`amount - self._shield_strength`) is calculated, `self._shield_strength` is set to 0, and the remaining damage is forwarded to `super().take_damage(remaining_damage)` so the parent class logic handles health reduction and boundary conditions correctly.
4. **Overriding `get_damage`**: If `_shield_strength > 0`, we add `5` to the result of `super().get_damage()`. Otherwise, we just return `super().get_damage()` (or use `self._base_damage`).
5. **Overriding `get_details`**: We call `super().get_details()` to get the base details string and concatenate `f" [Shield: {self._shield_strength}]"` to it.

PastPaper.markingScheme

### Mark Breakdown:

* **Class Header & Inheritance (1 Mark):**
* **1 Mark**: Correct syntax for declaring subclass `ShieldedEnemy` inheriting from `Enemy`.

* **Constructor Implementation (3 Marks):**
* **1 Mark**: Constructor header accepts exactly 4 arguments (`self`, `name`, `health`, `base_damage`, `shield_strength`).
* **1 Mark**: Call to parent class constructor `super().__init__(name, health, base_damage)` or equivalent base call.
* **1 Mark**: Correctly initializing `self._shield_strength` with the passed argument.

* **Overriding `take_damage` (5 Marks):**
* **1 Mark**: Overriding method header matches `take_damage(self, amount)` exactly.
* **1 Mark**: Conditional check `if amount <= self._shield_strength:` (or equivalent logic).
* **1 Mark**: Correct reduction of `self._shield_strength` if shield can absorb all damage.
* **1 Mark**: Setting `self._shield_strength` to `0` when damage exceeds shield.
* **1 Mark**: Deducting remainder of damage from health correctly (either via calling `super().take_damage` or reducing `self._health` directly and clamping to 0).

* **Overriding `get_damage` (2 Marks):**
* **1 Mark**: Correct method check for active shield (`self._shield_strength > 0`).
* **1 Mark**: Returns correct base damage plus 5 when shield is active, and base damage otherwise.

* **Overriding `get_details` (2 Marks):**
* **1 Mark**: Correctly invokes parent class's `get_details()` method using `super().get_details()` or class name reference.
* **1 Mark**: Appends `" [Shield: X]"` correctly with the current shield strength.
PastPaper.question 2 · structured
11 PastPaper.marks
A skeleton program contains a global 1D array named `DataBuffer` of size 10, which stores positive integer job IDs. Empty slots in the buffer are represented by the value `0`.

You are required to write a new subroutine `CompactBuffer` that processes `DataBuffer` in-place.

The subroutine must shift all non-zero elements to the beginning (left-hand side) of the array, preserving their original relative order. All remaining positions at the end (right-hand side) of the array must be filled with `0`.

To gain full marks, your subroutine must:
- Modify the array in-place.
- NOT declare or use any auxiliary arrays, lists, or large temporary data structures.
- Operate with an auxiliary space complexity of \(O(1)\).

**Part 1**: Write the program code for the subroutine `CompactBuffer`. (8 marks)

**Part 2**: Trace the contents of the array `DataBuffer` at the end of each iteration of your main loop when `CompactBuffer` is executed on the following initial array of size 5: `[0, 8, 0, 3, 1]`. State the final state of the array. (3 marks)
PastPaper.showAnswers

PastPaper.workedSolution

### Solution

#### Part 1: Algorithm Design
To achieve an in-place array compaction without using extra memory, we use a two-pointer approach:
1. Maintain a `writePointer` starting at index `0`.
2. Iterate through the array using a `readPointer` from index `0` to the end.
3. Whenever the `readPointer` encounters a non-zero value:
- If `readPointer` is different from `writePointer`, copy the value from `DataBuffer[readPointer]` to `DataBuffer[writePointer]` and set `DataBuffer[readPointer]` to `0`.
- Increment `writePointer` by 1.
4. If `readPointer` is equal to `writePointer` (which happens at the very beginning if there are no leading zeros), we do not need to perform a self-overwrite or set to zero, but we still increment `writePointer`.

An alternative valid approach is to overwrite the elements sequentially first and then fill the remaining elements from `writePointer` to the end of the array with `0`.

#### Part 2: Trace
Starting with: `[0, 8, 0, 3, 1]`
- **Start**: `writePointer = 0`
- **Iteration 1** (`readPointer = 0`): Value is `0`. No change. Array: `[0, 8, 0, 3, 1]`
- **Iteration 2** (`readPointer = 1`): Value is `8`. Since `1 != 0`, `DataBuffer[0] = 8` and `DataBuffer[1] = 0`. `writePointer` becomes `1`. Array: `[8, 0, 0, 3, 1]`
- **Iteration 3** (`readPointer = 2`): Value is `0`. No change. Array: `[8, 0, 0, 3, 1]`
- **Iteration 4** (`readPointer = 3`): Value is `3`. Since `3 != 1`, `DataBuffer[1] = 3` and `DataBuffer[3] = 0`. `writePointer` becomes `2`. Array: `[8, 3, 0, 0, 1]`
- **Iteration 5** (`readPointer = 4`): Value is `1`. Since `4 != 2`, `DataBuffer[2] = 1` and `DataBuffer[4] = 0`. `writePointer` becomes `3`. Array: `[8, 3, 1, 0, 0]`

Final Array State: `[8, 3, 1, 0, 0]`

PastPaper.markingScheme

### Part 1: Subroutine Code (Max 8 marks)
- **1 mark**: Correct subroutine header defining a parameter for the array/buffer (or correctly modifying a global array).
- **1 mark**: Initialization of a write pointer/index tracking variable to `0` (or the start index).
- **1 mark**: Loop structures created to traverse the entirety of the array exactly once (from index `0` to length-1).
- **1 mark**: Conditional statement checking if the current element is not equal to `0`.
- **2 marks**: Correct logic for shifting elements (1 mark for moving the non-zero element to the write pointer index, 1 mark for incrementing the write pointer correctly).
- **1 mark**: Correct logic for setting abandoned positions to `0` without destroying valid data (either dynamically during the shift, or via a second trailing loop from `writePointer` to the end of the array).
- **1 mark**: Code executes strictly in-place with no additional arrays or structures declared (auxiliary space complexity of \(O(1)\)).

### Part 2: Trace (Max 3 marks)
- **2 marks**: Accurate step-by-step trace showing changes to indices after each non-zero move. (Deduct 1 mark for any incorrect intermediate array state).
- **1 mark**: Correct final array state: `[8, 3, 1, 0, 0]`.
PastPaper.question 3 · Iterative Logic Modification
4.5 PastPaper.marks
An incomplete AQA A Level skeleton program contains a function `CheckValidMove` designed to validate the movement of a game piece on a square grid of size `BoardSize` \times `BoardSize`.

The current implementation of this function only checks if the destination coordinates are within the boundaries of the board:

```python
def CheckValidMove(CurrentRow, CurrentColumn, NewRow, NewColumn, BoardSize):
if NewRow < 0 or NewRow >= BoardSize or NewColumn < 0 or NewColumn >= BoardSize:
return False
return True
```

**Your Task:**
Modify the logic of `CheckValidMove` so that a move is only valid if:
1. The destination is within the board boundaries (as currently verified).
2. The move is strictly orthogonal (horizontal or vertical, but **not** diagonal or stationary).
3. The distance of the move is exactly 1 step (i.e., the piece moves exactly one square up, down, left, or right from its current position).

Write the updated Python function reflecting these requirements.
PastPaper.showAnswers

PastPaper.workedSolution

The modified function first retains the boundary check. Next, it computes the absolute differences between the current and proposed coordinates. To ensure an orthogonal move of exactly one step, one of the differences must be exactly 1 while the other must be exactly 0.

An alternative valid expression for the logic is checking if `RowDifference + ColumnDifference == 1` while ensuring both individual differences are non-negative integers (which is guaranteed by the absolute value function and coordinate system).

```python
def CheckValidMove(CurrentRow, CurrentColumn, NewRow, NewColumn, BoardSize):
if NewRow < 0 or NewRow >= BoardSize or NewColumn < 0 or NewColumn >= BoardSize:
return False

RowDiff = abs(NewRow - CurrentRow)
ColDiff = abs(NewColumn - CurrentColumn)

return (RowDiff + ColDiff) == 1
```

PastPaper.markingScheme

- **1 Mark**: Calculates absolute coordinate differences correctly (using `abs` or comparable manual difference checks).
- **1 Mark**: Implements a logical check ensuring only one of the dimensions changes by exactly 1, and the other remains unchanged (or checks that total absolute difference sum is equal to 1).
- **1 Mark**: Retains the existing out-of-bounds check correctly without breaking logic flow.
- **1.5 Marks**: Returns `True` and `False` correctly for all test cases (no syntax/logic bugs, handles non-movement and diagonals correctly).
PastPaper.question 4 · Iterative Logic Modification
4.5 PastPaper.marks
In a skeleton program, a circular queue is implemented using an array `Queue` of size `MaxQueueSize`, with pointers `Front` and `Rear`, and an integer `NumberInQueue` to keep track of the current quantity of items.

The existing `Enqueue` subroutine is implemented as follows:

```python
def Enqueue(NewItem, Queue, Front, Rear, NumberInQueue, MaxQueueSize):
if NumberInQueue == MaxQueueSize:
print("Queue Full")
else:
Rear = (Rear + 1) % MaxQueueSize
Queue[Rear] = NewItem
NumberInQueue = NumberInQueue + 1
return Front, Rear, NumberInQueue
```

**Your Task:**
Modify this subroutine to implement basic priority enqueuing.
- If the first character of `NewItem` is `'P'`, it is a priority item. Priority items must be placed at the **front** of the queue.
- To insert at the front: Decrement `Front` circularly (e.g., `Front = (Front - 1 + MaxQueueSize) % MaxQueueSize`), place the item at `Queue[Front]`, and increment `NumberInQueue`.
- Non-priority items (first character is not `'P'`) should follow the existing enqueue behavior (added to the rear).
- In both cases, the program must first check if the queue is full and print `"Queue Full"` if so.

Write the updated Python subroutine reflecting these requirements.
PastPaper.showAnswers

PastPaper.workedSolution

The function must check if the first character of the item is `'P'`. If so, it decrements the `Front` pointer circularly: `(Front - 1 + MaxQueueSize) % MaxQueueSize` (adding `MaxQueueSize` avoids negative indices in Python, although Python handles negative modulo natively, this is standard defensive programming for AQA pseudocode translation). It then assigns the element to `Queue[Front]`.
Otherwise, it executes the standard rear-insertion logic. Both execution paths increment `NumberInQueue` by 1.

```python
def Enqueue(NewItem, Queue, Front, Rear, NumberInQueue, MaxQueueSize):
if NumberInQueue == MaxQueueSize:
print("Queue Full")
else:
if NewItem[0] == 'P':
Front = (Front - 1) % MaxQueueSize
Queue[Front] = NewItem
else:
Rear = (Rear + 1) % MaxQueueSize
Queue[Rear] = NewItem
NumberInQueue = NumberInQueue + 1
return Front, Rear, NumberInQueue
```

PastPaper.markingScheme

- **1 Mark**: Correctly identifies a priority item by checking if the first character of `NewItem` is `'P'` (e.g., `NewItem[0] == 'P'`).
- **1 Mark**: Correctly decrements `Front` circularly using modulo arithmetic (allowing index wrapping below 0).
- **1 Mark**: Correctly assigns `NewItem` to the newly updated position (`Queue[Front]` for priority, `Queue[Rear]` for standard) and increments `NumberInQueue` in both cases.
- **1.5 Marks**: Preserves outer structured error-handling (`Queue Full` check) and ensures all variables (`Front`, `Rear`, `NumberInQueue`) are updated and returned correctly according to their respective conditional pathways.
PastPaper.question 5 · Screen Evidence of Testing
1 PastPaper.marks
You have modified a skeleton program to include a validation routine for a new custom game initialization setting. The routine prompts the user with "Enter starting energy: " and expects an integer between 10 and 50 inclusive. If the input is outside this range, it displays "Invalid energy level" and prompts again.

To provide screen evidence of testing for this modification, a developer plans a test run where they enter the invalid value 5, followed by another invalid value 55, and finally the valid value 20.

How many times in total will the prompt "Enter starting energy: " appear on the screen during this test run if the validation loop functions correctly?
PastPaper.showAnswers

PastPaper.workedSolution

1. The program starts and the first prompt appears. The user enters 5 (invalid as it is < 10).
2. The validation routine displays "Invalid energy level" and shows the prompt a second time. The user enters 55 (invalid as it is > 50).
3. The validation routine displays "Invalid energy level" and shows the prompt a third time. The user enters 20 (valid as it is within [10, 50]).
4. The validation loop terminates successfully.

Thus, the prompt appears exactly 3 times.

PastPaper.markingScheme

1 mark: Correct integer 3 (accept "3" or "three").
Reject any other numbers.
PastPaper.question 6 · Screen Evidence of Testing
1 PastPaper.marks
A binary search tree (BST) implementation in a skeleton program has been modified to support a "Find Minimum" command, option M. When M is selected, the program finds and displays the minimum key currently stored in the tree.

For testing, a BST is constructed by inserting keys in the following order: 15, 8, 22, 4, 11, 20, 27. To prove the "Find Minimum" feature works correctly, you run the program, insert these keys, and then enter command M.

What is the exact numerical value that must be displayed as the minimum key to provide correct screen evidence of testing?
PastPaper.showAnswers

PastPaper.workedSolution

When the keys [15, 8, 22, 4, 11, 20, 27] are inserted into a Binary Search Tree:
- 15 becomes the root.
- 8 goes to the left of 15.
- 22 goes to the right of 15.
- 4 goes to the left of 8.
- 11 goes to the right of 8.
- 20 goes to the left of 22.
- 27 goes to the right of 22.

The minimum element in a binary search tree is found by starting at the root and repeatedly following the left-child pointers until a node with no left child is reached. Following this path (15 -> 8 -> 4) leads to 4. Therefore, the minimum key value displayed on the screen must be 4.

PastPaper.markingScheme

1 mark: Correct numerical value of 4 (accept "4" or "four").
Reject any other values.
PastPaper.question 7 · Screen Evidence of Testing
1 PastPaper.marks
You have modified a queue-based scheduling simulation in a skeleton program to implement "priority queuing". Any string element starting with the characters "PR_" is automatically inserted at the front of the queue, while all other string elements are appended to the rear (back) of the queue.

The queue currently contains elements ["A", "B", "C"] in order from front to back.

As a test, the user performs the following operations:
1. Enqueue "PR_X"
2. Enqueue "D"
3. Dequeue one element and display its value on the screen.

What string value must be shown as dequeued on the screen to provide evidence that the priority queuing logic works correctly?
PastPaper.showAnswers

PastPaper.workedSolution

Let's trace the state of the queue:
- Initial state: front ["A", "B", "C"] back
- Enqueue "PR_X": Since "PR_X" starts with "PR_", it is inserted at the front of the queue. The queue becomes: front ["PR_X", "A", "B", "C"] back
- Enqueue "D": Since "D" does not start with "PR_", it is appended to the back. The queue becomes: front ["PR_X", "A", "B", "C", "D"] back
- Dequeue: The item at the front of the queue is removed. This item is "PR_X".

Therefore, the screen must display "PR_X" to show successful prioritisation.

PastPaper.markingScheme

1 mark: Correct string PR_X (accept with or without quotation marks, case-sensitive).
Reject lowercase modifications or other strings.
PastPaper.question 8 · Screen Evidence of Testing
1 PastPaper.marks
You have modified a Run-Length Encoding (RLE) compression routine in a skeleton program. The modification states that characters with a run-length of 1 must not be prefixed with their count (e.g., "A" is printed instead of "1A"), while characters with a run-length greater than 1 are prefixed with their count (e.g., "AAAA" is compressed to "4A").

To provide screen evidence of testing, you run the modified subprogram with the input string "WWWWX".

What is the exact compressed string output that must be visible on the screen to show that your modification is working correctly?
PastPaper.showAnswers

PastPaper.workedSolution

Let's analyze the input string "WWWWX":
- The character 'W' appears 4 times consecutively. Because the run-length is greater than 1, it should be compressed to its count followed by the character: "4W".
- The character 'X' appears 1 time consecutively. Because the run-length is exactly 1, no count prefix is added: "X".
- Combining these results yields "4WX".

Thus, the correct screen output must show "4WX".

PastPaper.markingScheme

1 mark: "4WX" (case-sensitive).
Reject "4W1X", "4wx", or any other variations.
PastPaper.question 9 · numerical
1 PastPaper.marks
In a 2D physics simulation, two moving particles have velocity vectors \(\mathbf{u} = \begin{bmatrix} 4 \\ -3 \end{bmatrix}\) and \(\mathbf{v} = \begin{bmatrix} 5 \\ 2 \end{bmatrix}\) respectively. Calculate the dot product (scalar product) \(\mathbf{u} \cdot \mathbf{v}\).
PastPaper.showAnswers

PastPaper.workedSolution

To calculate the dot product of two vectors, we multiply their corresponding components and sum the results. For \(\mathbf{u} = [4, -3]^T\) and \(\mathbf{v} = [5, 2]^T\), the calculation is: \(\mathbf{u} \cdot \mathbf{v} = (4 \times 5) + (-3 \times 2)\). This simplifies to: \(20 - 6 = 14\).

PastPaper.markingScheme

1 mark for 14. Reject any other values.
PastPaper.question 10 · numerical
1 PastPaper.marks
In a game's physics engine, a game object has an initial position vector \(\mathbf{p} = \begin{bmatrix} -3 \\ 8 \end{bmatrix}\). The object's position is updated by adding a displacement vector which is equal to \(4\) times the direction vector \(\mathbf{d} = \begin{bmatrix} 2 \\ -1.5 \end{bmatrix}\). Calculate the new y-coordinate of the game object.
PastPaper.showAnswers

PastPaper.workedSolution

First, scale the direction vector by multiplying each component by 4: \(4 \mathbf{d} = \begin{bmatrix} 4 \times 2 \\ 4 \times -1.5 \end{bmatrix} = \begin{bmatrix} 8 \\ -6 \end{bmatrix}\). Next, add the resulting scaled vector to the initial position vector: \(\mathbf{p'} = \begin{bmatrix} -3 \\ 8 \end{bmatrix} + \begin{bmatrix} 8 \\ -6 \end{bmatrix} = \begin{bmatrix} 5 \\ 2 \end{bmatrix}\). The y-coordinate is the second element of this position vector, which is 2.

PastPaper.markingScheme

1 mark for 2. Accept 2 or 2.0.

Paper 2 Standard Paper

Answer all theoretical and computational questions. Calculators are permitted.
26 PastPaper.question · 79.2 PastPaper.marks
PastPaper.question 1 · Calculations & Representations
2.5 PastPaper.marks
A computer uses a normalized 12-bit floating-point representation with an 8-bit mantissa and a 4-bit exponent, both in two's complement.
Convert the binary pattern \(01101100\ 0011\) to its denary representation. Show all your working.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Identify the components:**
- The mantissa is the first 8 bits: \(01101100\).
- The exponent is the remaining 4 bits: \(0011\).

2. **Evaluate the exponent:**
- The exponent binary is \(0011\), which represents a positive denary value of \(3\).

3. **Evaluate the mantissa:**
- Because the mantissa is positive (starts with 0), it is interpreted directly.
- Placing a binary point after the first bit: \(0.1101100\).
- In denary, this is: \(\frac{1}{2} + \frac{1}{4} + \frac{1}{16} + \frac{1}{32} = 0.5 + 0.25 + 0.0625 + 0.03125 = 0.84375\).

4. **Apply the exponent to the mantissa:**
- Shift the binary point 3 places to the right (since exponent is \(+3\)): \(0.1101100 \times 2^3 = 110.1100\).
- \(110.11_2 = 4 + 2 + 0.5 + 0.25 = 6.75\).

PastPaper.markingScheme

- **1 Mark:** Correctly converting the exponent of \(0011\) to the denary value \(3\).
- **1 Mark:** Correctly interpreting the mantissa as \(0.84375\) (or moving the binary point correctly by 3 positions to get \(110.11\)).
- **0.5 Marks:** Final correct answer of \(6.75\) (or equivalent fraction \(6\frac{3}{4}\)).
PastPaper.question 2 · Calculations & Representations
2.5 PastPaper.marks
An audio engineer is recording a high-fidelity stereo (2 channels) audio track. The recording settings are:
- Sample rate: \(48\text{ kHz}\)
- Bit depth: \(24\text{ bits}\) per sample
- Duration: \(3\text{ minutes}\) and \(20\text{ seconds}\)

Calculate the uncompressed file size of the audio track in Megabytes (MB). Assume \(1\text{ MB} = 1,000,000\text{ bytes}\). Show your working and round your final answer to one decimal place.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Determine total duration in seconds:**
\(3 \times 60 + 20 = 200\text{ seconds}\).

2. **Calculate total number of bits:**
\(\text{File Size in bits} = \text{Sample Rate (Hz)} \times \text{Bit Depth} \times \text{Channels} \times \text{Duration (seconds)}\)
\(\text{File Size} = 48,000 \times 24 \times 2 \times 200 = 460,800,000\text{ bits}\).

3. **Convert bits to bytes:**
\(\text{File Size in bytes} = 460,800,000 / 8 = 57,600,000\text{ bytes}\).

4. **Convert bytes to Megabytes (MB):**
Using standard base-10 conversion as specified (\(1\text{ MB} = 1,000,000\text{ bytes}\)):
\(57,600,000 / 1,000,000 = 57.6\text{ MB}\).

PastPaper.markingScheme

- **1 Mark:** Correctly identifying the duration as 200 seconds and writing a valid formula for total bits/bytes calculation.
- **1 Mark:** Correct intermediate calculation of total bytes (\(57,600,000\text{ bytes}\)) or total bits (\(460,800,000\text{ bits}\)).
- **0.5 Marks:** Correct final calculation of \(57.6\text{ MB}\) rounded correctly.
PastPaper.question 3 · Calculations & Representations
2.5 PastPaper.marks
Simplify the following Boolean expression using Boolean identities and laws:
\[Q = \overline{A \cdot B} \cdot (\bar{A} + B)\]
Show each step of your simplification.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Apply De Morgan's Law** to the term \(\overline{A \cdot B}\):
\(\overline{A \cdot B} = \bar{A} + \bar{B}\)
So, \(Q = (\bar{A} + \bar{B}) \cdot (\bar{A} + B)\)

2. **Apply the Distributive Law** (or expand the brackets):
\(Q = (\bar{A} \cdot \bar{A}) + (\bar{A} \cdot B) + (\bar{B} \cdot \bar{A}) + (\bar{B} \cdot B)\)

3. **Simplify terms** using identities:
- \(\bar{A} \cdot \bar{A} = \bar{A}\) (Idempotent Law)
- \(\bar{B} \cdot B = 0\) (Complement Law)
This simplifies the expression to:
\(Q = \bar{A} + \bar{A}B + \bar{A}\bar{B} + 0\)

4. **Factor out \(\bar{A}\)**:
\(Q = \bar{A}(1 + B + \bar{B})\)
Since \(1 + X = 1\) (Annihilation Law):
\(Q = \bar{A}(1) = \bar{A}\).

PastPaper.markingScheme

- **1 Mark:** Applying De Morgan's Law correctly to obtain \((\bar{A} + \bar{B})\).
- **1 Mark:** Showing appropriate step-by-step expansion/factoring using standard identities (e.g., recognizing \(\bar{B} \cdot B = 0\) and factoring out \(\bar{A}\)).
- **0.5 Marks:** Reaching the final simplified expression \(\bar{A}\) (or \(\text{NOT } A\)).
PastPaper.question 4 · Calculations & Representations
2.5 PastPaper.marks
Two 2D vectors are defined as:
\[\mathbf{u} = \begin{bmatrix} 3 \\ 4 \end{bmatrix}, \quad \mathbf{v} = \begin{bmatrix} 5 \\ 12 \end{bmatrix}\]

Calculate:
(a) The dot product \(\mathbf{u} \cdot \mathbf{v}\).
(b) The cosine of the angle \(\theta\) between the two vectors.
Show your working.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Calculate the dot product:**
\(\mathbf{u} \cdot \mathbf{v} = (3 \times 5) + (4 \times 12) = 15 + 48 = 63\).

2. **Calculate magnitudes of both vectors:**
- \(\|\mathbf{u}\| = \sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5\)
- \(\|\mathbf{v}\| = \sqrt{5^2 + 12^2} = \sqrt{25} + 144 = \sqrt{169} = 13\)

3. **Calculate the cosine of the angle:**
\(\cos(\theta) = \frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\| \|\mathbf{v}\|} = \frac{63}{5 \times 13} = \frac{63}{65} \approx 0.9692\).

PastPaper.markingScheme

- **1 Mark:** Correct working and evaluation of the dot product to get 63.
- **1 Mark:** Correct calculations of the vector magnitudes (5 and 13).
- **0.5 Marks:** Correctly substituting values into the cosine angle formula to obtain \(\frac{63}{65}\) (or approx \(0.97\)).
PastPaper.question 5 · Calculations & Representations
2.5 PastPaper.marks
A hash table of size 100 (indices 0 to 99) uses the **folding method** to map 6-digit keys to table indices. This implementation splits the key into three 2-digit groups, sums them, and then applies the modulo 100 operation to the sum.

Calculate the hash table index for the key `482937`. Show your working.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Split the 6-digit key into three 2-digit groups:**
- `482937` becomes `48`, `29`, and `37`.

2. **Sum the groups:**
- \(\text{Sum} = 48 + 29 + 37\)
- \(48 + 29 = 77\)
- \(77 + 37 = 114\)

3. **Apply the modulo 100 operation:**
- \(114 \pmod{100} = 14\).

Therefore, the hash table index is 14.

PastPaper.markingScheme

- **1 Mark:** Correctly splitting the key into three parts: 48, 29, and 37.
- **1 Mark:** Correctly summing the groups to get 114.
- **0.5 Marks:** Correct application of modulo 100 to yield 14.
PastPaper.question 6 · Calculations & Representations
2.5 PastPaper.marks
A string "ABRACADABRA" (containing exactly 11 characters) is encoded.
- In standard ASCII representation, each character requires 8 bits.
- When encoded using a custom Huffman code, the character codes are:
- 'A': `0`
- 'B': `10`
- 'R': `110`
- 'C': `1110`
- 'D': `1111`

Calculate the percentage reduction in file size (compression ratio) achieved by using this Huffman code instead of ASCII. Show your working and round your answer to one decimal place.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Calculate ASCII size:**
\(11\text{ characters} \times 8\text{ bits/char} = 88\text{ bits}\).

2. **Calculate Huffman size:**
Find the frequency of each unique character in "ABRACADABRA":
- 'A': occurs 5 times. Size = \(5 \times 1\text{ bit} = 5\text{ bits}\).
- 'B': occurs 2 times. Size = \(2 \times 2\text{ bits} = 4\text{ bits}\).
- 'R': occurs 2 times. Size = \(2 \times 3\text{ bits} = 6\text{ bits}\).
- 'C': occurs 1 time. Size = \(1 \times 4\text{ bits} = 4\text{ bits}\).
- 'D': occurs 1 time. Size = \(1 \times 4\text{ bits} = 4\text{ bits}\).
Total Huffman size = \(5 + 4 + 6 + 4 + 4 = 23\text{ bits}\).

3. **Calculate percentage reduction:**
- \(\text{Saving in bits} = 88 - 23 = 65\text{ bits}\).
- \(\text{Percentage saving} = \frac{65}{88} \times 100 \approx 73.8636\%\).
- Rounded to 1 decimal place: \(73.9\%\).

PastPaper.markingScheme

- **1 Mark:** Correct calculations of uncompressed size (88 bits) and Huffman compressed size (23 bits).
- **1 Mark:** Showing the correct division formula for compression ratio or savings percentage (\(\frac{88-23}{88} \times 100\)).
- **0.5 Marks:** Correct final percentage of \(73.9\%\) (accept \(26.1\%\) if calculated as remaining size ratio \(\frac{23}{88} \times 100\)).
PastPaper.question 7 · Calculations & Representations
2.5 PastPaper.marks
An organization is assigned the classless IPv4 address block `192.168.10.0/26`.
(a) Write down the subnet mask in dotted decimal notation.
(b) Calculate the maximum number of usable host IP addresses that can be assigned to devices on this subnet.
Show your working.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Determine the subnet mask:**
- A prefix of `/26` means that the first 26 bits are set to 1, and the remaining 6 bits are set to 0.
- In binary: `11111111.11111111.11111111.11000000`
- Converting to decimal: `255.255.255.192`.

2. **Determine the number of usable hosts:**
- The number of host bits \(n = 32 - 26 = 6\).
- Total addresses in this subnet = \(2^n = 2^6 = 64\).
- Since the first address is the network identifier and the last is the broadcast address, we subtract 2.
- \(\text{Usable hosts} = 2^6 - 2 = 64 - 2 = 62\).

PastPaper.markingScheme

- **1 Mark:** Correct subnet mask in dotted decimal notation: `255.255.255.192`.
- **1 Mark:** Correctly using the formula \(2^n - 2\) with \(n = 6\).
- **0.5 Marks:** Correct final value of 62 usable host addresses.
PastPaper.question 8 · Calculations & Representations
2.5 PastPaper.marks
Perform the subtraction of hexadecimal values `4D` minus `1F` using 8-bit two's complement binary arithmetic.

Show your working by:
1. Converting both hexadecimal values to 8-bit binary representation.
2. Finding the two's complement of the subtrahend (`1F`).
3. Performing the binary addition and converting your final answer back into hexadecimal.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Convert hex to 8-bit binary:**
- Minuend: `4D` = `0100 1101`
- Subtrahend: `1F` = `0001 1111`

2. **Find the two's complement of `1F` (`0001 1111`):**
- Flip the bits: `1110 0000`
- Add 1: `1110 0001` (representing `-1F` in decimal \(-31\))

3. **Perform addition:**
```
01001101 (4D)
+ 11100001 (-1F)
----------
100101110
```
Since we are using 8-bit arithmetic, the 9th bit (the leftmost carry bit) is discarded, yielding `0010 1110`.

4. **Convert back to hexadecimal:**
- `0010` = `2`
- `1110` = `E` (decimal 14)
Result = `2E`.

PastPaper.markingScheme

- **1 Mark:** Correctly converting `4D` to binary (`01001101`) and deriving the correct two's complement of `1F` as `11100001`.
- **1 Mark:** Executing the binary addition correctly to obtain the 8-bit binary string `00101110`.
- **0.5 Marks:** Correctly converting the binary result back to hexadecimal `2E`.
PastPaper.question 9 · Calculations & Representations
2.5 PastPaper.marks
A computer system represents floating-point numbers using a normalized 12-bit format: an 8-bit mantissa followed by a 4-bit exponent. Both mantissa and exponent are represented in two's complement.

Convert the following 12-bit binary representation into its decimal equivalent:

`10110100 0011`

Show your working.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Analyze the Exponent:**
The exponent is the last 4 bits: `0011`.
Since the MSB is 0, it is positive.
`0011` in binary is equal to \(+3\) in decimal.

2. **Analyze the Mantissa:**
The mantissa is the first 8 bits: `10110100`.
Since this is a normalized floating-point representation, the binary point is implied after the most significant bit: `1.0110100`.
The MSB is 1, which indicates a negative number.

To find the value of `1.0110100` in two's complement:
Using place values:
- Weight of MSB (sign bit) = \(-2^0 = -1\)
- Remaining bits: \((0 \times 2^{-1}) + (1 \times 2^{-2}) + (1 \times 2^{-3}) + (0 \times 2^{-4}) + (1 \times 2^{-5}) + (0 \times 2^{-6}) + (0 \times 2^{-7})\)
- Value = \(-1 + 0.25 + 0.125 + 0.03125 = -0.59375\)

Alternatively, using the "invert and add 1" method on the magnitude:
- Invert bits of `1.0110100` \u2192 `0.1001011`
- Add 1 to the least significant bit \u2192 `0.1001100`
- Convert `0.1001100` to decimal: \(2^{-1} \times 0 + 2^{-2} \times 1 + 2^{-3} \times 0 + 2^{-4} \times 0 + 2^{-5} \times 1 + 2^{-6} \times 1 = 0.25 + 0.03125 + 0.015625 = 0.59375\)
- Apply negative sign \u2192 \(-0.59375\)

3. **Calculate the Final Value:**
Multiply the mantissa by \(2^{\text{exponent}}\):
\[ \text{Value} = -0.59375 \times 2^3 = -0.59375 \times 8 = -4.75 \]

PastPaper.markingScheme

- **1 Mark**: Correct conversion of the exponent to \(3\) (or shifting the binary point 3 places to the right).
- **1 Mark**: Correct conversion of the two's complement mantissa to its decimal fractional value \(-0.59375\) (or equivalent fraction \(-\frac{19}{32}\)).
- **0.5 Marks**: Correct final answer of \(-4.75\) (or equivalent fraction \(-\frac{19}{4}\)).
PastPaper.question 10 · Calculations & Representations
2.5 PastPaper.marks
Two 3-dimensional vectors are represented as 1D arrays:

$$\mathbf{a} = [3, -1, 4]$$
$$\mathbf{b} = [k, 5, -2]$$

If the dot product $\mathbf{a} \cdot \mathbf{b} = 11$, calculate the value of the scalar $k$. Show your working.
PastPaper.showAnswers

PastPaper.workedSolution

1. **Recall the Dot Product Formula:**
The dot product of two 3-dimensional vectors $\mathbf{u} = [u_1, u_2, u_3]$ and $\mathbf{v} = [v_1, v_2, v_3]$ is calculated as:
$$\mathbf{u} \cdot \mathbf{v} = (u_1 \times v_1) + (u_2 \times v_2) + (u_3 \times v_3)$$

2. **Set up the Equation for $\mathbf{a}$ and $\mathbf{b}$:**
$$\mathbf{a} \cdot \mathbf{b} = (3 \times k) + (-1 \times 5) + (4 \times -2)$$
$$\mathbf{a} \cdot \mathbf{b} = 3k - 5 - 8$$
$$\mathbf{a} \cdot \mathbf{b} = 3k - 13$$

3. **Solve for $k$:**
Since we are given that $\mathbf{a} \cdot \mathbf{b} = 11$:
$$3k - 13 = 11$$
$$3k = 11 + 13$$
$$3k = 24$$
$$k = 8$$

PastPaper.markingScheme

- **1 Mark**: Correctly setting up the dot product equation using the vector components, e.g., \(3k - 5 - 8 = 11\).
- **1 Mark**: Correct rearrangement and simplification of the equation, arriving at \(3k = 24\).
- **0.5 Marks**: Correct final value of \(k = 8\).
PastPaper.question 11 · Structured Analytical Essay
9 PastPaper.marks
A municipal authority is implementing a smart city network consisting of millions of environmental and traffic sensors. This system generates massive streams of real-time data.

Discuss the challenges of managing and processing this data with reference to the three key characteristics of Big Data: **Volume**, **Velocity**, and **Variety**.

Evaluate why traditional relational database management systems (RDBMS) are poorly suited for this application compared to a Big Data architecture that uses a distributed file system and "schema-on-read".
PastPaper.showAnswers

PastPaper.workedSolution

### Model Answer Structure

**1. Application of the Three Vs to the Scenario:**
* **Volume:** The system consists of millions of sensors. If each sensor transmits data once per second, the cumulative daily volume will scale rapidly into terabytes or petabytes. Traditional localized storage will quickly run out of capacity.
* **Velocity:** Data is generated continuously and in real-time. The processing system must ingest, parse, and potentially act upon millions of incoming data packets per second without causing bottlenecks.
* **Variety:** Sensors from different manufacturers or monitoring different metrics (noise, particulate matter, vehicle speeds) will transmit data in multiple formats (e.g., XML, JSON, CSV, binary streams, or geospatial formats).

**2. Limitations of Traditional RDBMS:**
* **Schema-on-write:** RDBMS require a rigid, predefined database schema. If a new type of sensor is added with different attributes, the database schema must be altered, which can cause downtime and scale issues.
* **Scaling Limits (Vertical Scaling):** RDBMS typically scale vertically (upgrading a single server's CPU, RAM, or storage). This is extremely expensive and eventually hits physical hardware limits.
* **Write Bottlenecks and ACID Compliance:** RDBMS enforce ACID properties (Atomicity, Consistency, Isolation, Durability) through locking mechanisms. High-velocity concurrent writes from millions of sensors will lead to severe write locks and latency.

**3. Advantages of Big Data Architecture:**
* **Distributed File Systems (e.g., HDFS):** Allows data to be distributed across clusters of commodity hardware. This supports horizontal scaling (adding more cheap servers) which can scale indefinitely to handle growing volume and velocity.
* **Schema-on-read:** Raw data is written to the distributed storage in its native format without validation. The structure (schema) is applied only when the data is read or queried. This easily accommodates the wide variety of sensor data formats and allows for rapid, non-blocking ingestion.

PastPaper.markingScheme

### Banded Mark Scheme

**Level 3 (7-9 Marks):**
* The candidate provides a detailed and balanced discussion of all three characteristics (Volume, Velocity, Variety) specifically applied to the smart city scenario.
* Explains clearly why an RDBMS is structurally unsuited (focusing on vertical scaling, write bottlenecks, and schema constraints).
* Provides a robust evaluation of Big Data alternatives, clearly defining the role of distributed systems and the concept of 'schema-on-read'.
* Technical terminology is used accurately throughout.

**Level 2 (4-6 Marks):**
* The candidate explains the three characteristics of Big Data, but the application to the scenario may be general.
* Identifies some limitations of RDBMS (e.g., scaling or schemas) and mentions distributed storage or schema-on-read, but the comparison lacks depth or technical precision.
* Minor inaccuracies in terminology may be present.

**Level 1 (1-3 Marks):**
* The candidate defines some of the three Vs but fails to apply them to the scenario.
* Mentions RDBMS or Big Data architectures superficially without detailing why one is preferred over the other.

### Indicative Content Points to Reward:
* **Volume:** TBs/PBs of sensor data; storage exhausting quickly.
* **Velocity:** Real-time streams; necessity for high-ingest rates.
* **Variety:** Multi-structured data (JSON, XML, binary, GPS coordinates).
* **RDBMS Limits:** Pre-defined schema requirement; vertical scaling ceiling; transactional locking slowing down concurrent writes.
* **Big Data Solutions:** Horizontal scaling (commodity hardware); distributed processing (e.g., MapReduce concept); schema-on-read allowing rapid write speeds and flexible analysis.
PastPaper.question 12 · Structured Analytical Essay
9 PastPaper.marks
A major retail bank plans to replace its manual credit-assessment process with an automated machine-learning system. This system will analyze applicants' banking transactions, social media footprints, and geodemographic profiling to instantly decide whether to approve or deny loans.

Analyze the ethical, legal, and cultural implications of implementing this automated decision-making system. In your answer, you should refer to relevant UK legislation (such as the Data Protection Act 2018 / GDPR) and discuss the potential impact on fairness and societal trust.
PastPaper.showAnswers

PastPaper.workedSolution

### Model Answer Structure

**1. Ethical Implications:**
* **Algorithmic Bias and Discrimination:** Machine learning models are trained on historical data. If past manual decisions reflected socioeconomic, racial, or gender-based biases, the algorithm will codify and perpetuate these inequalities. Geodemographic profiling may lead to 'redlining', where individuals are unfairly penalized based on where they live rather than their personal creditworthiness.
* **Privacy and Proportionality:** Analyzing an applicant's social media footprint represents a massive intrusion into their private life. Social media activities are rarely representative of financial reliability, leading to ethically questionable profiling.
* **Lack of Transparency (The "Black Box"):** Deep learning algorithms are often uninterpretable, making it impossible to explain *why* an applicant was rejected, denying them fair recourse.

**2. Legal Implications (UK DPA 2018 / GDPR):**
* **Article 22 (Automated individual decision-making):** Under the GDPR, individuals have the right not to be subject to a decision based solely on automated processing which produces legal or similarly significant effects. The bank must ensure a lawful exception applies (such as explicit consent or necessity for entering a contract) and must offer the customer the right to obtain human intervention, express their point of view, and contest the decision.
* **Data Minimization:** Under the data protection principles, data collected must be adequate, relevant, and limited to what is necessary. Using social media data for a credit check is highly likely to violate this principle, as it is non-essential and disproportionate.
* **Fairness and Transparency:** The bank must provide clear privacy notices explaining that automated decision-making is occurring and details about the logic involved.

**3. Cultural and Social Implications:**
* **Erosion of Societal Trust:** Moving away from human-centric, empathetic banking to automated "computer says no" logic can isolate customers and erode trust in financial institutions.
* **Normalization of Surveillance:** Requiring social media and transaction-level monitoring normalizes continuous digital surveillance, shifting cultural expectations of privacy.
* **Digital Exclusion:** Vulnerable groups or those without an extensive digital/social media footprint may find themselves locked out of mainstream financial services, worsening socioeconomic divides.

PastPaper.markingScheme

### Banded Mark Scheme

**Level 3 (7-9 Marks):**
* The candidate presents a well-structured, balanced essay covering ethical, legal, and cultural implications in detail.
* Demonstrates precise knowledge of UK legislation (specifically referencing GDPR/DPA 2018 principles like Article 22 on automated decision-making and the principle of data minimization).
* Effectively links the technology (machine learning, profiling, social media scraping) to its real-world societal consequences (bias, exclusion, trust).

**Level 2 (4-6 Marks):**
* The candidate addresses at least two of the categories (ethical, legal, cultural) with reasonable detail.
* Mentions data protection legislation, but may not reference specific details like Article 22, right to explanation, or data minimization clearly.
* Explains some consequences (like bias or privacy) but the discussion of societal or cultural impacts is less developed.

**Level 1 (1-3 Marks):**
* The candidate makes superficial comments about fairness or privacy.
* Fails to accurately reference legislation or concrete ethical/cultural issues beyond generic statements (e.g., "hackers might steal the data" or "it is bad to judge people").

### Indicative Content Points to Reward:
* **Ethical:** Algorithmic bias (historical bias reinforcement); transparency/explainability (black-box algorithms); moral status of scraping social media data.
* **Legal (GDPR / DPA 2018):** Right to human intervention (Article 22); Data minimization (is social media profiling necessary?); Right to be informed (transparency of algorithms).
* **Cultural:** Digital divide/exclusion (disadvantage for unbanked or digitally inactive individuals); loss of human contact/empathy in services; cultural shift toward accepted surveillance.
PastPaper.question 13 · written
2.4 PastPaper.marks
A server has a single public IP address but runs both an HTTPS web server (port 443) and an SSH server (port 22). Describe how the Transport layer of the TCP/IP stack uses port numbers to ensure incoming packets are delivered to the correct application service.
PastPaper.showAnswers

PastPaper.workedSolution

1. The Transport layer protocol (TCP/UDP) inspects the segment header of the incoming packet to identify the destination port number.
2. This port number acts as an identifier for a specific service or application process currently running on the server.
3. The Transport layer uses this port to map the data stream to the correct socket or application port, allowing concurrent communication with multiple services via a single physical IP address.

PastPaper.markingScheme

1 mark: Identifying that the transport layer/protocol (TCP/UDP) inspects the destination port in the segment header.
1 mark: Explaining that this port maps/routes the incoming data to a specific socket or active application process (e.g., 443 to web server, 22 to SSH).
0.4 marks: Mentioning that this allows a single IP address to demultiplex/handle multiple independent network services simultaneously.
PastPaper.question 14 · written
2.4 PastPaper.marks
Explain why Network Address Translation (NAT) is standard practice in networks using IPv4, and explain why the introduction of IPv6 removes the technical necessity for NAT.
PastPaper.showAnswers

PastPaper.workedSolution

1. IPv4 addresses are 32 bits, leading to an address exhaustion issue. NAT allows a private local network to share one public IP address by mapping internal IP/port combinations to the external IP.
2. IPv6 addresses are 128 bits long, providing \(3.4 \times 10^{38}\) unique addresses.
3. Because of this massive pool, every single device can be allocated its own globally unique public IP address, allowing direct end-to-end routing without NAT.

PastPaper.markingScheme

1 mark: Explaining that IPv4 address space is limited (32-bit), requiring NAT to share a single public IP among multiple local private IPs.
1 mark: Explaining that IPv6 uses 128-bit addresses, which provides a virtually unlimited number of unique global addresses.
0.4 marks: Concluding that because every device can have its own unique public IP, end-to-end direct communication is possible, removing the need for NAT.
PastPaper.question 15 · written
2.4 PastPaper.marks
Explain the fundamental physical difference between baseband and broadband data transmission over a communication channel.
PastPaper.showAnswers

PastPaper.workedSolution

1. In baseband transmission, digital signals (pulses of electricity or light) are sent directly over the medium without modulation. The entire capacity (bandwidth) of the cable is dedicated to a single communication channel at any one time.
2. In broadband transmission, analog signals are modulated at different carrier frequencies. By dividing the total available bandwidth into separate frequency bands (Frequency Division Multiplexing), multiple independent streams of data can travel along the same physical medium concurrently.

PastPaper.markingScheme

1 mark: Defining baseband as using the entire channel bandwidth for a single digital signal/stream without modulation.
1 mark: Defining broadband as dividing the channel bandwidth into multiple frequency bands using modulation (Frequency Division Multiplexing).
0.4 marks: Clearly contrasting the two (e.g., baseband carries one signal at a time, broadband carries multiple parallel signals simultaneously).
PastPaper.question 16 · written
2.4 PastPaper.marks
A host on an Ethernet LAN wants to send a packet to another host with a known IP address on the same subnet, but its local ARP cache does not contain the target's MAC address. Describe how the Address Resolution Protocol (ARP) resolves this.
PastPaper.showAnswers

PastPaper.workedSolution

1. The sending host constructs an ARP Request packet containing the target IP address and broadcasts it to the MAC broadcast address (FF:FF:FF:FF:FF:FF) so all devices on the local network receive it.
2. All devices receive and process the broadcast, but only the host whose IP address matches the one in the ARP request responds.
3. This target host sends a unicast ARP Reply directly back to the sender's MAC address, containing its physical MAC address. The sender then stores this mapping in its local ARP cache.

PastPaper.markingScheme

1 mark: Stating that an ARP request is broadcast to all devices on the local network containing the target IP.
1 mark: Stating that only the host with the matching IP address responds with a unicast ARP reply containing its MAC address.
0.4 marks: Explaining that the sender then records/caches this IP-to-MAC mapping in its local ARP cache for future frames.
PastPaper.question 17 · written
2.4 PastPaper.marks
When a client computer requests a domain name resolution, its local DNS resolver can perform either a recursive query or an iterative query. Explain the difference in operation between these two query methods from the perspective of the local DNS resolver.
PastPaper.showAnswers

PastPaper.workedSolution

1. Recursive: The client asks the local DNS resolver to find the IP. The resolver does all the work, querying root, TLD, and authoritative servers, and returns the final IP or an error back to the client.
2. Iterative: The DNS server queried by the local resolver does not contact other servers. If it doesn't know the answer, it returns a referral containing the IP of another DNS server (e.g., a TLD server) that is closer to the destination. The local resolver must then make a new query to that referred server.

PastPaper.markingScheme

1 mark: Describing recursive queries: the resolver/queried server handles the entire resolution process, tracking down the final IP address on behalf of the client.
1 mark: Describing iterative queries: the queried server returns a referral (the address of the next DNS server down the hierarchy) rather than resolving it itself, forcing the requester to make the subsequent query.
0.4 marks: Clearly stating that in recursive queries the burden of finding the result is on the queried server, while in iterative queries the burden is on the querying client/resolver.
PastPaper.question 18 · written
2.4 PastPaper.marks
CSMA/CD is widely used in wired Ethernet networks to handle medium access, whereas wireless networks (802.11) use CSMA/CA. Explain how CSMA/CA works to avoid collisions, and explain why CSMA/CD is not practical in wireless environments.
PastPaper.showAnswers

PastPaper.workedSolution

1. CSMA/CA mechanism: A station listens to the wireless medium. If the channel is idle, it waits for a short period (IFS) plus a random back-off time before transmitting. It may also use the RTS/CTS handshake to reserve the medium and prevent collision.
2. In wireless networks, transmitting signals are much stronger than incoming signals. A wireless radio cannot easily detect a weak incoming collision signal while it is actively transmitting a strong signal (hidden node problem and half-duplex hardware limitations). Hence, collision detection (CD) is unviable, making collision avoidance (CA) necessary.

PastPaper.markingScheme

1 mark: Explaining CSMA/CA collision avoidance: node senses channel, waits a random back-off period if busy, and uses RTS/CTS (Request to Send / Clear to Send) handshake to reserve the channel before transmitting.
1 mark: Explaining why CSMA/CD is not practical in wireless: a wireless transmitter's own signal drowns out any other signals, making simultaneous transmission and collision detection impossible on a single antenna (half-duplex).
0.4 marks: Mentioning the 'hidden node' problem where two nodes can't hear each other but both can hear the access point, rendering carrier sensing alone insufficient to detect collisions.
PastPaper.question 19 · written
2.4 PastPaper.marks
Describe the three steps of the TCP 3-way handshake used to establish a connection between a client and a server, explicitly referencing the flags and sequence numbers used.
PastPaper.showAnswers

PastPaper.workedSolution

1. Step 1 (SYN): The client sends a TCP segment to the server with the SYN (Synchronise) flag set and an Initial Sequence Number (e.g., \(x\)).
2. Step 2 (SYN-ACK): The server receives the segment and responds with a segment where both the SYN and ACK flags are set. It includes its own Initial Sequence Number (e.g., \(y\)) and an Acknowledgement Number set to \(x + 1\).
3. Step 3 (ACK): The client receives the SYN-ACK and sends an ACK segment with the Acknowledgement Number set to \(y + 1\) to complete the connection.

PastPaper.markingScheme

1 mark: Explaining Step 1 (SYN sent by client with an initial sequence number x).
1 mark: Explaining Step 2 (SYN-ACK sent by server with its own sequence number y, and acknowledging x by sending acknowledgement number x + 1).
0.4 marks: Explaining Step 3 (ACK sent by client acknowledging y by sending acknowledgement number y + 1 to establish the connection).
PastPaper.question 20 · written
2.4 PastPaper.marks
A host with IP address 192.168.1.35 and subnet mask 255.255.255.224 wants to send a packet to IP address 192.168.1.61. Explain the bitwise mathematical operation the host performs to determine if the destination host is on its local subnet or requires a router.
PastPaper.showAnswers

PastPaper.workedSolution

1. The sending host performs a bitwise AND operation between its own IP address (192.168.1.35) and the subnet mask (255.255.255.224).
- 35 in binary: 00100011
- 224 in binary: 11100000
- Bitwise AND: 00100000 (which is 32). So the network ID is 192.168.1.32.
2. The host performs a bitwise AND operation between the destination IP address (192.168.1.61) and the subnet mask (255.255.255.224).
- 61 in binary: 00111101
- 224 in binary: 11100000
- Bitwise AND: 00100000 (which is 32). So the destination's network ID is 192.168.1.32.
3. Because the two calculated network addresses are identical (192.168.1.32), the host concludes the destination is on the local subnet and transmits directly via MAC address rather than routing.

PastPaper.markingScheme

1 mark: Explaining the bitwise AND operation between the sender's IP and subnet mask to determine the local network address.
1 mark: Explaining that the same bitwise AND is performed on the destination's IP and subnet mask, and the two resulting network addresses are compared.
0.4 marks: Correctly calculating that both yield the same network address (192.168.1.32), meaning the destination is on the local subnet.
PastPaper.question 21 · short_answer
2.2 PastPaper.marks
Explain what is meant by 'referential integrity' in the context of relational databases and state how it is maintained.
PastPaper.showAnswers

PastPaper.workedSolution

Referential integrity ensures consistency between related tables. If table A has a foreign key referencing table B, every value in that foreign key column must correspond to an existing primary key in table B, or be null. This prevents orphaned records and maintains relational consistency. It is enforced through foreign key constraints implemented by the DBMS.

PastPaper.markingScheme

1 Mark: Defining referential integrity as ensuring consistency between linked tables or ensuring no orphaned records (every foreign key must match a valid primary key or be NULL).
1.2 Marks: Explaining how it is maintained (e.g., through DBMS enforcement of foreign key constraints, preventing deletion of parent records, or cascading deletes/updates).
PastPaper.question 22 · short_answer
2.2 PastPaper.marks
A relational database contains the following two tables:

`Student(StudentID, FirstName, LastName)`

`Enrolment(EnrolmentID, StudentID, CourseName, EnrolmentDate)`

Write an SQL query to retrieve the `LastName` and the total number of enrolments (aliased as `TotalCourses`) for every student who has enrolled in at least one course. Group the results by `StudentID` and `LastName`.
PastPaper.showAnswers

PastPaper.workedSolution

The query requires a join between `Student` and `Enrolment` on the common attribute `StudentID`. Since we want the number of courses per student, we use the aggregate function `COUNT()` and group by both `StudentID` (to uniquely identify the student) and `LastName` (to display it). Aliasing is done with `AS TotalCourses`.

PastPaper.markingScheme

1 Mark: Correct SELECT clause with COUNT and alias, and GROUP BY clause.
1.2 Marks: Correct FROM clause with INNER JOIN / JOIN and matching ON condition.
PastPaper.question 23 · short_answer
2.2 PastPaper.marks
A database table is designed with the following attributes:

`Booking(BookingID, CustomerID, HotelID, HotelName, HotelAddress)`

The primary key is `BookingID`. Explain why this table is not in Third Normal Form (3NF) and identify the change needed to bring it to 3NF.
PastPaper.showAnswers

PastPaper.workedSolution

For a table to be in 3NF, all non-key attributes must be dependent on the key, the whole key, and nothing but the key (no transitive dependencies). In this case, `HotelName` and `HotelAddress` are determined by `HotelID`, which is a non-key attribute in this table. This is a transitive dependency (\(BookingID \rightarrow HotelID \rightarrow HotelName, HotelAddress\)). To normalise, separate into `Booking(BookingID, CustomerID, HotelID)` and `Hotel(HotelID, HotelName, HotelAddress)`.

PastPaper.markingScheme

1 Mark: Explaining that a transitive dependency exists because `HotelName`/`HotelAddress` depend on the non-key attribute `HotelID` (or are not dependent solely on the primary key `BookingID`).
1.2 Marks: Explaining the correction (creating a separate `Hotel` table with `HotelID` as primary key, leaving `HotelID` as a foreign key in `Booking`).
PastPaper.question 24 · short_answer
2.2 PastPaper.marks
In a multi-user client-server database system, concurrent access to the same record can cause data integrity issues. Describe how 'record locking' resolves this issue, and explain how a 'deadlock' can occur as a consequence of record locking.
PastPaper.showAnswers

PastPaper.workedSolution

Record locking ensures serialization by locking a record when a transaction begins modifying it, preventing other transactions from writing to or reading from it until the first transaction completes (commits or rolls back). However, if Transaction A locks Record 1 and needs Record 2 to complete, and Transaction B locks Record 2 and needs Record 1 to complete, both transactions are blocked indefinitely waiting for each other, resulting in a deadlock.

PastPaper.markingScheme

1 Mark: Explaining record locking (temporary lock on a record during modification to prevent concurrent edits and maintain consistency).
1.2 Marks: Explaining deadlock (two or more transactions blocked indefinitely, each holding a lock the other needs to proceed).
PastPaper.question 25 · short_answer
2.2 PastPaper.marks
A relational database has a table named `Inventory` with attributes: `ItemID` (Primary Key), `ItemName`, `Category`, and `Price`.

Write an SQL query to reduce the `Price` of all items in the 'Electronics' category by 15%.
PastPaper.showAnswers

PastPaper.workedSolution

To update existing records, the `UPDATE` statement is used. The target table is `Inventory`. The `SET` clause is used to calculate the new price by multiplying the existing price by 0.85 (a 15% reduction). The `WHERE` clause restricts the change to records where `Category` is equal to 'Electronics'.

PastPaper.markingScheme

1 Mark: Correct UPDATE and SET clause (`UPDATE Inventory SET Price = Price * 0.85` or equivalent subtraction syntax).
1.2 Marks: Correct WHERE clause (`WHERE Category = 'Electronics'`).
PastPaper.question 26 · Assembly Trace Table
6 PastPaper.marks
An assembly language program is executed on a processor that uses the standard AQA Assembly Language instruction set.

The instruction set used in this program is defined as follows:
- `LDR Rd, `: Load the value from the specified memory address into register Rd.
- `STR Rd, `: Store the value from register Rd into the specified memory address.
- `MOV Rd, `: Copy the value of the operand into register Rd.
- `ADD Rd, Rn, `: Add the value of the operand to the value in register Rn and store the result in register Rd.
- `SUB Rd, Rn, `: Subtract the value of the operand from the value in register Rn and store the result in register Rd.
- `CMP Rn, `: Compare the value in register Rn with the operand.
- `B `: Unconditionally branch to the instruction at the specified label.
- `BLT `: Branch to the instruction at the specified label if the comparison result was "less than".
- `HALT`: Stop execution of the program.

Before the program starts, the memory locations contain the following denary values:
- Memory address 150 contains: 11
- Memory address 151 contains: 3
- Memory address 152 contains: 0
- Memory address 153 contains: 0

Below is the assembly language program:
```assembly
LDR R1, 150
LDR R2, 151
MOV R3, #0
loop:
CMP R1, R2
BLT end
SUB R1, R1, R2
ADD R3, R3, #1
B loop
end:
STR R1, 152
STR R3, 153
HALT
```

Trace this program by completing the table below. Write each change to a register or memory location on a new line in the trace table. Leave cells blank if their values do not change.
PastPaper.showAnswers

PastPaper.workedSolution

Let's trace the execution of the program step-by-step:

1. `LDR R1, 150` loads the value at memory address 150 (which is 11) into Register R1.
- State: R1 = 11

2. `LDR R2, 151` loads the value at memory address 151 (which is 3) into Register R2.
- State: R1 = 11, R2 = 3

3. `MOV R3, #0` loads the immediate value 0 into Register R3.
- State: R1 = 11, R2 = 3, R3 = 0

4. `loop: CMP R1, R2` compares R1 (11) and R2 (3).
- Since 11 is not less than 3, the `BLT end` instruction is not triggered.

5. `SUB R1, R1, R2` subtracts R2 from R1: 11 - 3 = 8. R1 is updated to 8.
- State: R1 = 8, R2 = 3, R3 = 0

6. `ADD R3, R3, #1` increments R3 by 1: 0 + 1 = 1. R3 is updated to 1.
- State: R1 = 8, R2 = 3, R3 = 1

7. `B loop` branches back to the start of the loop.

8. `CMP R1, R2` compares R1 (8) and R2 (3).
- Since 8 is not less than 3, the program does not branch.

9. `SUB R1, R1, R2` subtracts R2 from R1: 8 - 3 = 5. R1 is updated to 5.
- State: R1 = 5, R2 = 3, R3 = 1

10. `ADD R3, R3, #1` increments R3 by 1: 1 + 1 = 2. R3 is updated to 2.
- State: R1 = 5, R2 = 3, R3 = 2

11. `B loop` branches back.

12. `CMP R1, R2` compares R1 (5) and R2 (3).
- Since 5 is not less than 3, the program does not branch.

13. `SUB R1, R1, R2` subtracts R2 from R1: 5 - 3 = 2. R1 is updated to 2.
- State: R1 = 2, R2 = 3, R3 = 2

14. `ADD R3, R3, #1` increments R3 by 1: 2 + 1 = 3. R3 is updated to 3.
- State: R1 = 2, R2 = 3, R3 = 3

15. `B loop` branches back.

16. `CMP R1, R2` compares R1 (2) and R2 (3).
- Since 2 < 3, the `BLT end` branch is taken.

17. At `end: STR R1, 152` stores the value in R1 (2) into Memory address 152.
- State: Memory[152] = 2

18. `STR R3, 153` stores the value in R3 (3) into Memory address 153.
- State: Memory[153] = 3

19. `HALT` stops the program.

PastPaper.markingScheme

Marks are awarded as follows (up to a maximum of 6 marks):

- **1 Mark**: Correctly initializing R1 with 11, R2 with 3, and R3 with 0.
- **1 Mark**: Correctly updating R1 to 8 and R3 to 1 in the first loop iteration.
- **1 Mark**: Correctly updating R1 to 5 and R3 to 2 in the second loop iteration.
- **1 Mark**: Correctly updating R1 to 2 and R3 to 3 in the third loop iteration.
- **1 Mark**: Correctly stopping subtraction/increment cycles when R1 is less than R2 (2 < 3).
- **1 Mark**: Correctly writing the final stored values (Memory[152] = 2 and Memory[153] = 3).

*Note: Allow minor structural variations (e.g., writing multiple changes on a single row) as long as the sequential progression of values and the final state of all variables and memory locations are correct.*

PastPaper.sampleCTATitle

PastPaper.sampleCTADescription

PastPaper.sampleStickyMessage

PastPaper.stickyCtaText