AQA A-Level · Thinka 原創模擬試題

2023 AQA A-Level Computer Science 7517 模擬試題連答案詳解

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

200 300 分鐘2023
An original Thinka practice paper modelled on the structure and difficulty of the Jun 2023 AQA A Level Computer Science 7517 paper. Not affiliated with or reproduced from AQA.

卷一 甲部

Answer all questions. You must not use a calculator. Spend around 40 minutes on this section.
5 題目 · 37
題目 1 · Short Answer
7.4
An object-oriented program contains a base class called \(\text{Vehicle}\) and two subclasses, \(\text{ElectricCar}\) and \(\text{PetrolCar}\). The \(\text{Vehicle}\) class has a virtual method \(\text{calculateRange()}\). Both subclasses override this method.

Describe what is meant by **polymorphism** and **dynamic binding** in this context, and explain how they allow a list of \(\text{Vehicle}\) objects to be processed efficiently.
查看答案詳解

解題

### 1. Polymorphism in this context
- Polymorphism is the ability of different objects to respond to the same method call in different ways.
- In this scenario, the program can store objects of types \(\text{ElectricCar}\) and \(\text{PetrolCar}\) in a single collection of type \(\text{Vehicle}\). When the method \(\text{calculateRange()}\) is called on a reference of type \(\text{Vehicle}\), the correct subclass implementation (either electric or petrol) is executed.

### 2. Dynamic Binding (Late Binding)
- Dynamic binding is when the association between a method call and its actual implementation is made at runtime rather than at compile-time.
- The compiler does not hardcode the memory address of the function to execute. Instead, it is resolved during program execution based on the actual runtime object type of the vehicle.

### 3. Efficient Processing of the List
- Without polymorphism/dynamic binding, the programmer would have to write complex conditional structures (e.g., `if` or `switch` statements) to check the type of each vehicle in the list and call the corresponding specific method.
- With polymorphism, the program can simply iterate through a list of `Vehicle` objects using a simple loop and execute `vehicle.calculateRange()`. This reduces code complexity, eliminates execution overhead from multiple conditional checks, and makes the system easily extensible (e.g., adding a `HybridCar` subclass requires no changes to the processing loop).

評分準則

Award marks as follows (up to 7.4 marks total):
- **Up to 2 marks for Polymorphism**:
- 1 mark: Define polymorphism as the ability of different objects to respond to the same method call differently.
- 1 mark: Apply it to the scenario (e.g., calling `calculateRange()` on a `Vehicle` variable runs the specific overridden code in `ElectricCar` or `PetrolCar`).
- **Up to 2 marks for Dynamic Binding**:
- 1 mark: Define dynamic binding as resolving the association of a method call to its implementation at runtime (rather than compile-time).
- 1 mark: Explain that it uses the actual object type at execution time to find the correct memory location of the overridden method.
- **Up to 3.4 marks for Efficiency of processing**:
- 1 mark: Explain that it allows a single uniform loop to process a mixed list of `Vehicle` objects.
- 1 mark: Explain that it eliminates the need for conditional branches (e.g., `if-else` type-checking) to find the object's class.
- 1.4 marks: Explain that it facilitates high extensibility (new classes can be added without altering the loop code).
題目 2 · Short Answer
7.4
Explain the sequence of events that occurs when an hardware interrupt is detected during the Fetch-Decode-Execute (FDE) cycle.

Your answer must refer to the registers involved (including the Program Counter, Stack Pointer, and Status Register) and explain how the processor resumes execution of the interrupted program.
查看答案詳解

解題

### Step-by-Step Sequence of Events for an Interrupt:

1. **Detection and Priority Checking**:
- At the end of each Fetch-Decode-Execute (FDE) cycle, the CPU checks the interrupt lines / Interrupt Register to see if an interrupt signal has been raised.
- The processor compares the priority of the incoming interrupt with the priority of the current running task. If the interrupt has a higher priority, execution of the current program is temporarily suspended.

2. **Saving the State (Context Switch)**:
- The current state of the processor must be saved so execution can resume later.
- The contents of the **Program Counter (PC)** (which holds the address of the next instruction to execute in the main program) and the **Status Register** (SR) are saved.
- These values, along with other general-purpose registers, are pushed onto the system stack. The **Stack Pointer (SP)** register is decremented/incremented to point to the new top of the stack.

3. **Executing the ISR**:
- The processor determines the start address of the appropriate **Interrupt Service Routine (ISR)** by looking up the interrupt source in the Interrupt Vector Table.
- This address is loaded into the **Program Counter (PC)**.
- The CPU then begins executing instructions of the ISR (resuming normal FDE cycles for the ISR code).

4. **Restoring State & Resuming**:
- Once the ISR finishes executing, a return instruction (such as `RTI` - Return from Interrupt) is called.
- The CPU restores the previous state by popping the registers off the stack (using the **SP** to retrieve them) and placing them back into the **PC**, **Status Register**, and general registers.
- The processor resumes execution of the original program from the exact point it was suspended.

評分準則

Award marks as follows (up to 7.4 marks total):
- **1 mark**: CPU checks the interrupt line/register at the completion of each FDE instruction cycle.
- **1 mark**: CPU checks and compares the priority of the interrupt against the current task.
- **2 marks**: Current state is saved: Program Counter (PC) and Status Register (SR) are pushed onto the system stack, updating the Stack Pointer (SP) (1 mark for stack/SP concept, 1 mark for mentioning PC/SR).
- **2 marks**: The address of the Interrupt Service Routine (ISR) is loaded from the interrupt vector table into the PC (1 mark for vector table lookup, 1 mark for loading to PC).
- **1.4 marks**: The ISR executes, and upon completion, the saved register state is popped back from the stack to resume the main program.
題目 3 · Short Answer
7.4
A programmer writes a recursive function \(\text{processString}\) in pseudocode as follows:

```
SUB processString(s)
IF LEN(s) <= 1 THEN
RETURN s
ELSE
char1 = SUBSTRING(s, 0, 1) // first character
char2 = SUBSTRING(s, LEN(s)-1, 1) // last character
middle = SUBSTRING(s, 1, LEN(s)-2) // middle substring
IF char1 == char2 THEN
RETURN char1 + processString(middle)
ELSE
RETURN processString(middle) + char1
ENDIF
ENDIF
ENDSUB
```

*Note: \(\text{SUBSTRING(s, start, length)}\) extracts a substring starting at index \(\text{start}\) (0-indexed) with the specified \(\text{length}\).*

Trace the execution of \(\text{processString("abcca")}\) showing the recursive calls made, their parameters, and the return values from each call. State the final returned string.
查看答案詳解

解題

### Trace of recursive execution:

* **Call 1**: `processString("abcca")`
- `s = "abcca"`, `LEN(s) = 5`.
- `char1 = "a"`, `char2 = "a"`, `middle = "bcc"`.
- Since `char1 == char2` (`"a" == "a"` is True), the function executes the `IF` branch:
`RETURN "a" + processString("bcc")`.

* **Call 2**: `processString("bcc")`
- `s = "bcc"`, `LEN(s) = 3`.
- `char1 = "b"`, `char2 = "c"`, `middle = "c"`.
- Since `char1 == char2` (`"b" == "c"` is False), the function executes the `ELSE` branch:
`RETURN processString("c") + "b"`.

* **Call 3**: `processString("c")`
- `s = "c"`, `LEN(s) = 1`.
- Since `LEN(s) <= 1` is True, it enters the base case and executes:
`RETURN "c"`.

### Unwinding the recursion:
- **Call 3** returns `"c"`.
- **Call 2** returns `processString("c") + "b"` = `"c" + "b"` = `"cb"`.
- **Call 1** returns `"a" + processString("bcc")` = `"a" + "cb"` = `"acb"`.

**Final returned string**: `"acb"`

評分準則

Award marks as follows (up to 7.4 marks total):
- **2 marks**: Correctly traces Call 1 (`s = "abcca"`), identifying `char1 == char2` is True, and showing it returns `"a" + processString("bcc")`.
- **2 marks**: Correctly traces Call 2 (`s = "bcc"`), identifying `char1 != char2` is True, and showing it returns `processString("c") + "b"`.
- **2 marks**: Correctly traces Call 3 (`s = "c"`), identifying it as the base case and returning `"c"`.
- **1.4 marks**: Correctly calculates the unwinding process and states the final returned string is `"acb"`.
題目 4 · Short Answer
7.4
A Turing machine has states \(Q = \{S_0, S_1, S_2, S_{\text{halt}}\}\), where \(S_0\) is the start state. The input alphabet is \(\Sigma = \{0, 1\}\) and the tape alphabet is \(\Gamma = \{0, 1, \square\}\).

The transition function \(\delta\) is defined as:
* \(\delta(S_0, 1) = (S_0, 0, R)\)
* \(\delta(S_0, 0) = (S_1, 1, R)\)
* \(\delta(S_1, 1) = (S_1, 1, R)\)
* \(\delta(S_1, \square) = (S_2, \square, L)\)
* \(\delta(S_2, 1) = (S_{\text{halt}}, 0, R)\)

The initial tape contents are \(\dots \square \square 1 1 0 1 \square \square \dots\) with the tape head positioned over the leftmost '1'.

Trace the sequence of states, tape contents, and tape head positions step-by-step until the machine halts. State the final tape contents and the final position of the tape head.
查看答案詳解

解題

Let \([x]\) represent the symbol that the tape head is currently pointing to.

1. **Initial Configuration**:
- State: \(S_0\)
- Tape: `[1] 1 0 1`
- Transition: \(\delta(S_0, 1) = (S_0, 0, R)\). Replace `1` with `0`, transition to state \(S_0\), and move Right.

2. **Step 1**:
- State: \(S_0\)
- Tape: `0 [1] 0 1`
- Transition: \(\delta(S_0, 1) = (S_0, 0, R)\). Replace `1` with `0`, transition to state \(S_0\), and move Right.

3. **Step 2**:
- State: \(S_0\)
- Tape: `0 0 [0] 1`
- Transition: \(\delta(S_0, 0) = (S_1, 1, R)\). Replace `0` with `1`, transition to state \(S_1\), and move Right.

4. **Step 3**:
- State: \(S_1\)
- Tape: `0 0 1 [1]`
- Transition: \(\delta(S_1, 1) = (S_1, 1, R)\). Replace `1` with `1`, transition to state \(S_1\), and move Right.

5. **Step 4**:
- State: \(S_1\)
- Tape: `0 0 1 1 [\square]`
- Transition: \(\delta(S_1, \square) = (S_2, \square, L)\). Replace `\square` with `\square`, transition to state \(S_2\), and move Left.

6. **Step 5**:
- State: \(S_2\)
- Tape: `0 0 1 [1] \square`
- Transition: \(\delta(S_2, 1) = (S_{\text{halt}}, 0, R)\). Replace `1` with `0`, transition to state \(S_{\text{halt}}\), and move Right.

7. **Step 6 (Halted)**:
- State: \(S_{\text{halt}}\)
- Tape: `0 0 1 0 [\square]`

**Final Tape Contents**: `0010` (with blanks elsewhere)
**Final Head Position**: On the blank space `\square` directly to the right of the last `0`.

評分準則

Award marks as follows (up to 7.4 marks total):
- **2 marks**: Correct tracking of state \(S_0\) over the first two `1`s, converting them to `0`s and moving right.
- **2 marks**: Correct state transition to \(S_1\) when reading `0`, changing it to `1`, and moving right.
- **2 marks**: Correct movement over the `1` and handling of the blank symbol `\square` transitioning to state \(S_2\) and moving left.
- **1.4 marks**: Correct final transition at \(S_2\) changing the `1` to `0` and entering \(S_{\text{halt}}\) with tape head on the trailing blank.
題目 5 · Short Answer
7.4
A router on a local area network receives an IP packet. The destination IP address of the packet is `192.168.42.115` and the router's subnet mask is `255.255.255.224` (which can also be written in CIDR format as \(/27\)).

Explain how the router uses the subnet mask to determine the network ID of the destination address. Calculate both the **network address (subnet address)** and the **broadcast address** for this subnet, showing your working in binary.
查看答案詳解

解題

### Step 1: Explain the processing
To determine the network ID, the router performs a bitwise **AND** operation between the 32-bit destination IP address and the 32-bit subnet mask.

### Step 2: Binary Conversion of the Last Octet
Since the first three octets of the subnet mask are `255.255.255`, they are all binary `1`s (`11111111`), meaning they do not change during a bitwise AND. We only need to convert and calculate the 4th octet:
- **IP 4th octet**: `115` in binary is `01110011` (since \(64 + 32 + 16 + 2 + 1 = 115\)).
- **Subnet mask 4th octet**: `224` in binary is `11100000` (since \(128 + 64 + 32 = 224\)).

### Step 3: Network Address Calculation
Perform bitwise AND on the 4th octet:
```
0 1 1 1 0 0 1 1 (115)
AND
1 1 1 0 0 0 0 0 (224)
-----------------
0 1 1 0 0 0 0 0 (96)
```
Convert `01100000` back to denary: \(64 + 32 = 96\).
Therefore, the **Network Address** is **`192.168.42.96`**.

### Step 4: Broadcast Address Calculation
The broadcast address is found by taking the network ID and setting all host bits (the bits where the subnet mask has `0`s) to `1`s.
In our 4th octet, the first 3 bits are network bits (`011`), and the last 5 bits are host bits (`00011`).
- Setting the last 5 bits of the network octet to `1`s: `01111111`.
- Convert `01111111` back to denary: \(64 + 32 + 16 + 8 + 4 + 2 + 1 = 127\).
Therefore, the **Broadcast Address** is **`192.168.42.127`**.

評分準則

Award marks as follows (up to 7.4 marks total):
- **2 marks**: Explain that the router uses a bitwise AND operation on the binary IP address and subnet mask to extract the network ID.
- **2 marks**: Correct conversion and calculation of the Network Address:
- 1 mark for showing binary working: `01110011 AND 11100000 = 01100000`.
- 1 mark for correct final address: `192.168.42.96`.
- **2 marks**: Correct conversion and calculation of the Broadcast Address:
- 1 mark for showing binary working (setting host bits to 1): `01111111`.
- 1 mark for correct final address: `192.168.42.127`.
- **1.4 marks**: Explain that the router uses the resulting network ID to determine if the destination is on the local subnet (direct delivery) or needs forwarding to an external gateway router.

卷一 乙部

Write a program starting from a new program/project/file based on the provided specifications.
1 題目 · 13
題目 1 · Practical Programming
13

Write a program to validate and process DNA sequences.

Your program must meet the following requirements:

  1. Repeatedly prompt the user to enter a DNA sequence. The program must terminate if the user enters an empty string.
  2. For each entered sequence, perform the following validation checks:
    • Verify that the sequence contains only the characters 'A', 'C', 'G', and 'T' (case-insensitive).
    • Verify that the length of the sequence is greater than 0 and a multiple of 3.
    • If the sequence fails any check, display a descriptive error message indicating the reason for failure (e.g., "invalid characters", "invalid length", or both) and prompt the user again.
  3. If the sequence is valid, split the sequence into codons (groups of 3 characters).
  4. Analyse and classify each codon according to these rules:
    • "ATG" is classified as "Start".
    • "TAA", "TAG", and "TGA" are classified as "Stop".
    • Any other group of 3 valid characters is classified as "Amino Acid".
  5. Output each codon alongside its classification.
  6. At the end of processing the sequence, output the total count of "Amino Acid" codons found in that sequence (excluding "Start" and "Stop" codons).
查看答案詳解

解題

An example of a complete Python program that meets all the requirements:

while True:
seq = input("Enter DNA sequence (or press Enter to quit): ").upper()
if seq == "":
break

# Validation
valid_chars = True
for char in seq:
if char not in ["A", "C", "G", "T"]:
valid_chars = False
break

valid_len = len(seq) > 0 and len(seq) % 3 == 0

if not valid_chars or not valid_len:
if not valid_chars and not valid_len:
print("Error: Sequence contains invalid characters and length is not a multiple of 3.")
elif not valid_chars:
print("Error: Sequence contains invalid characters. Only A, C, G, T allowed.")
else:
print("Error: Sequence length must be a multiple of 3 and greater than 0.")
continue

# Processing and Output
amino_count = 0
print("
--- Codon Analysis ---")
for i in range(0, len(seq), 3):
codon = seq[i:i+3]
if codon == "ATG":
classification = "Start"
elif codon in ["TAA", "TAG", "TGA"]:
classification = "Stop"
else:
classification = "Amino Acid"
amino_count += 1
print(f"Codon {i//3 + 1}: {codon} -> {classification}")

print(f"Total Amino Acid codons: {amino_count}
")

評分準則

  • Input and Control Loop (3 Marks):
    • 1 mark: Correct implementation of an infinite loop (e.g., while True) that cleanly breaks when the user inputs an empty string.
    • 1 mark: Converts input sequence to uppercase to guarantee case-insensitive handling.
    • 1 mark: Program continues to prompt the user after handling validation errors.
  • Validation (4 Marks):
    • 1 mark: Correctly checks that the length of the string is greater than 0 and a multiple of 3.
    • 1 mark: Correctly checks that all characters in the string are valid ('A', 'C', 'G', 'T').
    • 1 mark: Uses boolean flags or logical structures to prevent invalid strings from proceeding to analysis.
    • 1 mark: Output displays helpful, contextual error feedback identifying why the input was rejected.
  • Processing & Classification (4 Marks):
    • 1 mark: Correctly iterates through the valid string in steps of 3 to extract distinct substrings of length 3 (codons).
    • 1 mark: Correctly maps "ATG" to the "Start" classification.
    • 1 mark: Correctly maps "TAA", "TAG", and "TGA" to the "Stop" classification.
    • 1 mark: Correctly identifies all other combinations of valid bases as "Amino Acid".
  • Output & Counts (2 Marks):
    • 1 mark: Output lists each codon accompanied by its classification.
    • 1 mark: Accurately maintains and displays a count of only "Amino Acid" codons (excluding Start/Stop).

卷一 部分 C

Answer the questions based on the provided Preliminary Material and Skeleton Program without changing code.
6 題目 · 12.96
題目 1 · Short Answer
2.16
Based on the Preliminary Material and Skeleton Program representing a grid-based game, the constant MAX_GRID_SIZE is defined as 10. Explain why it is better practice to use the named constant MAX_GRID_SIZE throughout the code rather than using the literal value 10 directly.
查看答案詳解

解題

Using named constants instead of literal numbers (magic numbers) makes code easier to read as the identifier clarifies the purpose of the value. It also increases maintainability because any future changes to the grid size only need to be made once where the constant is declared, rather than searching and replacing all instances of the number 10.

評分準則

1 mark: Explains that named constants improve readability by giving meaning to the number. 1 mark: Explains that named constants improve maintainability as changes only need to be made in one location.
題目 2 · Short Answer
2.16
The Skeleton Program uses a global 2D array named Grid to represent the layout of the game. Describe why a 2D array is a more appropriate data structure for representing this grid compared to a 1D array of the same total capacity.
查看答案詳解

解題

A 2D array naturally models the two-dimensional Cartesian plane of the game grid. This allows developers to access cells directly using two intuitive indices (e.g., Grid[row][col]). A 1D array would require an indexing formula, such as index = row * width + col, which is less intuitive, harder to read, and more prone to programmer error.

評分準則

1 mark: Mentions direct or intuitive coordinate-based indexing (using row and column). 1 mark: Explains that it avoids the need for complex indexing formulas required by a 1D array.
題目 3 · Short Answer
2.16
The function IsMoveValid checks if a player can move to a new coordinate on the grid. State two validation checks that this function should perform before returning True.
查看答案詳解

解題

The function must first verify that the destination coordinates are within the legal index bounds of the grid (e.g., between 0 and MAX_GRID_SIZE - 1) to prevent an out-of-bounds index error. Secondly, it must check if the destination cell is currently traversable and not occupied by an obstacle, wall, or another entity.

評分準則

1 mark: Boundary check (ensuring coordinates are within valid array indices). 1 mark: Collision/obstacle check (ensuring target cell is not occupied or blocked).
題目 4 · Short Answer
2.16
The Skeleton Program reads initial map data from a text file. Explain why the subroutine that performs this file reading should use exception handling blocks.
查看答案詳解

解題

If the specified text file does not exist, is corrupted, or is locked by another process, a runtime exception will be raised. Using exception handling (e.g., try/except blocks) prevents the program from crashing and allows the developer to display a helpful error message or prompt the user to choose another file.

評分準則

1 mark: Prevents unexpected program crashes or abrupt termination. 1 mark: Enables graceful recovery, such as prompting for an alternative file path or showing a user-friendly error message.
題目 5 · Short Answer
2.16
The developer wants to keep track of the last 5 commands entered by the player using a queue data structure. Explain why a circular queue is more efficient than a linear queue for this purpose.
查看答案詳解

解題

In a linear queue, when the oldest element is removed (dequeued), all subsequent elements must be shifted forward to fill the vacant space, which is an O(N) operation. In a circular queue, the front and rear pointers simply wrap around using modulo arithmetic, keeping both enqueue and dequeue operations at O(1) time complexity with no elements needing to be moved.

評分準則

1 mark: Identifies that a linear queue requires shifting elements when dequeuing. 1 mark: Explains that a circular queue avoids shifting by updating pointers, resulting in constant O(1) time complexity.
題目 6 · Short Answer
2.16
The program needs to search the 10x10 Grid array to find the current coordinates of a key item ('K'). State why a binary search is not suitable for this task and name the search algorithm that should be used instead.
查看答案詳解

解題

Binary search requires the underlying dataset to be sorted in a particular order. Because the characters in the game grid are arranged according to spatial coordinates and not sorted alphabetically or numerically, binary search is impossible. A linear search (scanning through each cell of the 2D array sequentially) must be used instead.

評分準則

1 mark: Explains that binary search is not suitable because the data / grid is unsorted. 1 mark: Identifies linear (or sequential) search as the correct algorithm to use.

卷一 部分 D

Answer questions requiring you to modify the Skeleton Program and take screen captures of test runs.
4 題目 · 37
題目 1 · practical
9.25
This question refers to a Skeleton Program for a grid-based game where a player moves on a \(10 \times 10\) grid. The coordinates range from 0 to 9 for both row and column. The movement is handled by a subroutine called `MovePlayer`.

Currently, the program updates coordinates without verification, which can lead to index out-of-bounds exceptions or incorrect logical positions.

**Task:**
Modify the subroutine `MovePlayer` so that it prevents the player from moving off the edge of the grid.
- If a proposed movement would result in the player leaving the grid boundaries, the coordinate position of the player must remain unchanged.
- An error message `"Error: Move would take you out of bounds!"` must be printed to the screen.
- No fuel should be consumed for invalid moves (normally, each valid move costs 5 fuel).

Write the modified code for your `MovePlayer` subroutine.
查看答案詳解

解題

```python
def MovePlayer(Direction, PlayerX, PlayerY, Fuel):
NewX = PlayerX
NewY = PlayerY
if Direction == 'N':
NewY -= 1
elif Direction == 'S':
NewY += 1
elif Direction == 'W':
NewX -= 1
elif Direction == 'E':
NewX += 1

# Boundary verification
if NewX < 0 or NewX > 9 or NewY < 0 or NewY > 9:
print("Error: Move would take you out of bounds!")
else:
PlayerX = NewX
PlayerY = NewY
Fuel -= 5
return PlayerX, PlayerY, Fuel
```

評分準則

**Total Marks: 9.25**
- **3.0 Marks:** Correctly computing the potential next coordinates (`NewX`, `NewY`) before applying changes directly to player position variables.
- **3.0 Marks:** Using appropriate selection logical statements (e.g. `NewX < 0 or NewX > 9 or NewY < 0 or NewY > 9`) to identify out-of-bounds conditions.
- **1.25 Marks:** Outputting the exact required warning message text.
- **2.0 Marks:** Ensuring the fuel is only decremented by 5 if and only if the movement is structurally valid and within boundaries.
題目 2 · practical
9.25
This question refers to the game loop in the Skeleton Program where player input is processed.

**Task:**
Implement a "Fuel Boost" mechanic that can be activated once per game by typing the command `'B'` or `'b'`.
1. Initialise a boolean flag `BoostUsed` to `False` when a new game starts.
2. When command `'B'` or `'b'` is entered, verify whether `BoostUsed` is still `False`.
3. If it is `False`, add 50 units to `Fuel` up to a hard-capped maximum capacity of 150 units. Print the success message: `"Fuel boosted by up to 50 units!"` and set `BoostUsed` to `True`.
4. If `BoostUsed` is already `True`, output an error message: `"Error: Fuel boost already used this game!"`.

Write the code modifications required in your game logic subroutine to implement this feature.
查看答案詳解

解題

```python
# Inside game initialisation:
BoostUsed = False

# Inside user input processing block (e.g. PlayGame):
Command = input("Enter command: ").upper()
if Command == 'B':
if not BoostUsed:
Fuel = Fuel + 50
if Fuel > 150:
Fuel = 150
BoostUsed = True
print("Fuel boosted by up to 50 units!")
else:
print("Error: Fuel boost already used this game!")
```

評分準則

**Total Marks: 9.25**
- **2.0 Marks:** Declaring and correctly initialising `BoostUsed` to `False` at the appropriate scope level.
- **2.0 Marks:** Creating an input handler branch mapping `'B'` and `'b'` commands successfully.
- **2.25 Marks:** Verifying if the boost was previously active and executing the conditional state change to `True`.
- **3.0 Marks:** Incrementing the fuel capacity with a limit cap logic ensuring fuel does not exceed 150 units, and writing both correct output strings.
題目 3 · practical
9.25
This question refers to tracking program states using dynamic linear data structures.

**Task:**
Modify the Skeleton Program to trace, store, and display every coordinate location the player visits throughout their journey.
1. Initialise an empty list (or dynamic array) variable called `MovementHistory` containing only the starting coordinate pair `(0, 0)`.
2. Append the new tuple/record representation of `(PlayerX, PlayerY)` to `MovementHistory` every time a player makes a successful move.
3. Once the game ends (e.g., when fuel reaches 0 or a target destination is found), output the entire trajectory. The output format must match this format precisely:
`Path taken: (0,0) -> (0,1) -> (1,1)`

Write the modified code snippets demonstrating the data structure initialisation, the update code block, and the output loop logic.
查看答案詳解

解題

```python
# 1. Initialisation
MovementHistory = [(0, 0)]

# 2. Append step within movement logic loop
# After coordinate change is validated:
MovementHistory.append((PlayerX, PlayerY))

# 3. Trajectory Output Formatting
path_segments = []
for x, y in MovementHistory:
path_segments.append(f"({x},{y})")
print("Path taken: " + " -> ".join(path_segments))
```

評分準則

**Total Marks: 9.25**
- **2.0 Marks:** Correctly declaring and seeding the `MovementHistory` list with the initial coordinate pair structure.
- **2.25 Marks:** Appending player position records to the dynamic array ONLY upon successful, legal player movement updates.
- **3.0 Marks:** Using a loop to iterate through the history structure and dynamically construct the representation sequence.
- **2.0 Marks:** Ensuring the correct output presentation format matching `(X,Y) -> (X,Y)` without trailing pointers.
題目 4 · practical
9.25
This question refers to using exception handling and stream file I/O operations.

**Task:**
Create a new subroutine `SaveHighScore(PlayerName, Score)` that safely appends game results to a text file named `high_scores.txt`.
1. The routine must receive the player name and numerical final score as parameters.
2. Append the data to `high_scores.txt` in a CSV layout: `Name,Score` (e.g., `Alice,120`), followed by a newline.
3. If an input/output system exception occurs while opening or writing to the storage stream (such as a read-only permissions error or disk full state), the program must not crash. It must intercept the failure and output `"Error: Could not save high score."` via standard stream outputs.

Write the complete subroutine implementation code.
查看答案詳解

解題

```python
def SaveHighScore(PlayerName, Score):
try:
with open("high_scores.txt", "a") as File:
File.write(f"{PlayerName},{Score}
")
except IOError:
print("Error: Could not save high score.")
```

評分準則

**Total Marks: 9.25**
- **1.5 Marks:** Subroutine signature containing valid parameters for name and score.
- **2.25 Marks:** Accessing the external text file under appropriate append options (`'a'`), ensuring existing file contents are not overwritten.
- **2.0 Marks:** Formatting the written string elements sequentially separated by a comma and terminating with standard newline escapes.
- **2.0 Marks:** Utilising explicit code block exception handling captures (`try...except IOError` or equivalent framework Exception class).
- **1.5 Marks:** Displaying the exact warning string inside the rescue block segment.

卷二 甲部

Answer all questions. You may use a calculator. Spend 2 hours 30 minutes.
12 題目 · 100
題目 1 · Short Answer / Calculations
7.4
A specific processor has a 40-bit address bus and a 32-bit data bus. The main memory is byte-addressable. 1. Calculate the maximum size of memory, in Tebibytes (\(TiB\)), that can be directly addressed by this processor. Show your working. 2. Explain the purpose of the address bus during a write-to-memory operation.
查看答案詳解

解題

1. The maximum memory that can be addressed is \(2^{40}\) bytes. Since \(2^{10}\) B = 1 KiB, \(2^{20}\) B = 1 MiB, \(2^{30}\) B = 1 GiB, and \(2^{40}\) B = 1 TiB, the maximum addressable memory is exactly 1 Tebibyte (\(1\text{ TiB}\)). 2. During a write operation, the address bus is used to transmit the physical address of the specific memory location where the data is to be stored. This ensures the data reaches the correct destination.

評分準則

1. Award 2 marks for memory calculation: 1 mark for identifying the address capacity as \(2^{40}\) bytes, 1 mark for converting \(2^{40}\) bytes to exactly 1 TiB. 2. Award 5.4 marks for explanation of the address bus: up to 3 marks for describing that the address bus carries the physical location/address, and up to 2.4 marks for explaining how it selects/enables the specific memory word for writing.
題目 2 · Short Answer / Calculations
7.4
A computer system uses a normalized floating-point format with an 8-bit mantissa and a 4-bit exponent, both represented in two's complement. Convert the following representation to its decimal equivalent: Mantissa: 10110000, Exponent: 0110. Show your working.
查看答案詳解

解題

Mantissa: 10110000. In two's complement, the leftmost bit is the sign bit with a value of \(-1\). The mantissa represents the fraction: \(-1 + 0 \times 0.5 + 1 \times 0.25 + 1 \times 0.125 = -1 + 0.375 = -0.625\). Exponent: 0110. In two's complement, this represents a positive integer: \(4 + 2 = 6\). The calculation is: \(-0.625 \times 2^{6} = -0.625 \times 64 = -40\).

評分準則

Award 2 marks for converting the mantissa to decimal (\(-0.625\)). Award 2 marks for converting the exponent to decimal (\(6\)). Award 3.4 marks for evaluating the calculation correctly to arrive at \(-40\).
題目 3 · Short Answer / Calculations
7.4
An organisation's network uses the IPv4 address 192.168.41.88 with a subnet mask of 255.255.240.0. 1. Calculate the Network Identifier (Network ID) for this network. Show your calculation. 2. Calculate the maximum number of individual host addresses that can be assigned to devices on this subnet.
查看答案詳解

解題

1. Convert the third octet of both IP and mask to binary: IP: 41 = 00101001. Mask: 240 = 11110000. Bitwise AND: 00101001 AND 11110000 = 00100000 = 32 in decimal. Therefore, the Network ID is 192.168.32.0. 2. A subnet mask of 255.255.240.0 has 20 network bits (8+8+4) and 12 host bits (32 - 20). The number of host addresses is \(2^{12} - 2 = 4096 - 2 = 4094\) (subtracting 2 for the network and broadcast addresses).

評分準則

1. Award 3.4 marks for the Network ID: 1 mark for binary representation of 41 and 240, 1 mark for performing the AND operation, and 1.4 marks for the final IP representation of 192.168.32.0. 2. Award 4 marks for host address calculation: 2 marks for identifying there are 12 host bits, and 2 marks for calculating \(2^{12} - 2 = 4094\) (must subtract 2 for full marks).
題目 4 · Short Answer / Calculations
7.4
A Turing machine is defined with the states {S0, S1, S2} where S2 is the halting state. The transition table is: (S0, 1) -> (S0, 0, R); (S0, 0) -> (S1, 1, R); (S0, blank) -> (S2, blank, S); (S1, 1) -> (S1, 1, R); (S1, 0) -> (S0, 0, R); (S1, blank) -> (S2, blank, S). The tape initially contains '1 1 0 1 0' starting from the leftmost cell, with the write-head pointing at the leftmost '1' in state S0. Trace the execution of this Turing machine and write down the final state of the tape when it halts.
查看答案詳解

解題

Let's trace step-by-step: Step 0: Head at index 0 (val 1), State S0. Rule (S0, 1) -> (S0, 0, R). Tape: 0 1 0 1 0. Step 1: Head at index 1 (val 1), State S0. Rule (S0, 1) -> (S0, 0, R). Tape: 0 0 0 1 0. Step 2: Head at index 2 (val 0), State S0. Rule (S0, 0) -> (S1, 1, R). Tape: 0 0 1 1 0. Step 3: Head at index 3 (val 1), State S1. Rule (S1, 1) -> (S1, 1, R). Tape: 0 0 1 1 0. Step 4: Head at index 4 (val 0), State S1. Rule (S1, 0) -> (S0, 0, R). Tape: 0 0 1 1 0. Step 5: Head at index 5 (val blank), State S0. Rule (S0, blank) -> (S2, blank, S). Halts. Final tape state: 00110.

評分準則

Award 2 marks for correctly tracing the tape through the first two transitions (getting 0 0 0 1 0). Award 2 marks for tracing the S1 transition and write-head movement (getting 0 0 1 1 0). Award 3.4 marks for correctly identifying that the final tape output is 00110 when state S2 is reached.
題目 5 · Short Answer / Calculations
7.4
Simplify the following Boolean expression using the laws of Boolean algebra: \(Q = \overline{A \cdot B} \cdot (\bar{A} + B) \cdot (\bar{B} + B)\). Show each step of your simplification and state the names of the laws used.
查看答案詳解

解題

Step 1: Apply Complement Law to \(\bar{B} + B\), which is equal to 1. The expression becomes \(Q = \overline{A \cdot B} \cdot (\bar{A} + B) \cdot 1\). Step 2: Apply Identity Law to remove the 1: \(Q = \overline{A \cdot B} \cdot (\bar{A} + B)\). Step 3: Apply De Morgan's Law to \(\overline{A \cdot B}\) which becomes \(\bar{A} + \bar{B}\). The expression is now \(Q = (\bar{A} + \bar{B}) \cdot (\bar{A} + B)\). Step 4: Apply the Distributive Law in reverse (factoring out \(\bar{A}\)): \(Q = \bar{A} + (\bar{B} \cdot B)\). Step 5: Apply Complement Law to \(\bar{B} \cdot B\), which equals 0. Expression is \(Q = \bar{A} + 0\). Step 6: Apply Identity Law to get \(Q = \bar{A}\).

評分準則

Award 1.4 marks for simplifying \(\bar{B} + B = 1\). Award 2 marks for applying De Morgan's Law to \(\overline{A \cdot B}\). Award 2 marks for using the distributive law to reach \(\bar{A} + (\bar{B} \cdot B)\). Award 2 marks for final simplification to \(\bar{A}\) with reasons.
題目 6 · Short Answer / Calculations
7.4
A system is designed using object-oriented principles to model a car rental agency. An abstract class Vehicle is defined. A subclass Car and another subclass Truck inherit from Vehicle. The Vehicle class has an abstract method calculateRentalPrice(int days). 1. Explain the purpose of defining Vehicle as an abstract class rather than a concrete class. 2. Explain how polymorphism is demonstrated when calling calculateRentalPrice on different items stored in a list of type Vehicle.
查看答案詳解

解題

1. An abstract class cannot be instantiated directly, which matches reality because a generic 'Vehicle' cannot exist without being a specific type (like a Car or a Truck). It also acts as a template, forcing all subclasses to implement the calculateRentalPrice method. 2. Polymorphism allows the program to iterate through a list of Vehicles and call calculateRentalPrice on each object. At runtime, the correct implementation (Car's or Truck's version) is dynamically bound and executed depending on the actual type of the object, despite them being referenced as Vehicles.

評分準則

1. Award 3.7 marks for explaining the purpose of an abstract class (1.7 marks for stating it cannot be instantiated directly, 2 marks for stating it forces subclasses to implement required template methods). 2. Award 3.7 marks for explaining polymorphism (1.7 marks for mentioning dynamic/late binding at runtime, 2 marks for explaining that different implementations run based on the object's actual class despite being called via a uniform interface).
題目 7 · Short Answer / Calculations
7.4
A hash table of size 11 (with indexes 0 to 10) uses the hash function: h(key) = key mod 11. To resolve collisions, the hash table uses linear probing with an increment of 1. The following integer keys are inserted into an empty hash table in this order: 23, 45, 12, 34, 56. Show the state of the hash table after all keys have been inserted, listing the keys at each index from 0 to 10.
查看答案詳解

解題

Let's perform the insertions: 1. 23 mod 11 = 1. Slot 1 is empty, store 23. 2. 45 mod 11 = 1. Slot 1 is occupied, probe to slot 2. Slot 2 is empty, store 45. 3. 12 mod 11 = 1. Slots 1 and 2 are occupied, probe to slot 3. Slot 3 is empty, store 12. 4. 34 mod 11 = 1. Slots 1, 2, and 3 are occupied, probe to slot 4. Slot 4 is empty, store 34. 5. 56 mod 11 = 1. Slots 1, 2, 3, and 4 are occupied, probe to slot 5. Slot 5 is empty, store 56. Indexes 0 and 6 to 10 are empty.

評分準則

Award 2.4 marks for correctly placing 23 and 45 at indexes 1 and 2. Award 2.5 marks for correctly placing 12 and 34 at indexes 3 and 4. Award 2.5 marks for correctly placing 56 at index 5 and indicating that all other indexes (0, 6, 7, 8, 9, 10) are empty.
題目 8 · Short Answer / Calculations
7.4
In a functional programming language, the following standard functions are defined: map, filter, and foldr. Given: square x = x * x, isEven x = (x mod 2 == 0), add x y = x + y. Evaluate the expression: foldr add 0 (map square (filter isEven [1, 2, 3, 4, 5])). Show your working for each stage of the evaluation.
查看答案詳解

解題

Step 1: Evaluate filter isEven [1, 2, 3, 4, 5]. Since 2 and 4 are the only even numbers, this results in [2, 4]. Step 2: Evaluate map square [2, 4]. This applies square to each element: [square 2, square 4] = [4, 16]. Step 3: Evaluate foldr add 0 [4, 16]. This expands to: add 4 (add 16 0) = 4 + 16 = 20.

評分準則

Award 2.4 marks for filter evaluation resulting in [2, 4]. Award 2.5 marks for map evaluation resulting in [4, 16]. Award 2.5 marks for the foldr evaluation resulting in the final correct value of 20.
題目 9 · Calculation
7.4
A digital logic system has the Boolean output expression: \( F = A \cdot \overline{B} \cdot \overline{C} + A \cdot \overline{B} \cdot C + \overline{A} \cdot B \cdot \overline{C} + \overline{A} \cdot \overline{B} \cdot \overline{C} \). Simplify the expression \( F \) to its simplest sum-of-products form using Boolean algebra. Show each step of your simplification and state the laws you have applied at each stage.
查看答案詳解

解題

Step 1: Write down the expression: \( F = A\overline{B}\overline{C} + A\overline{B}C + \overline{A}B\overline{C} + \overline{A}\overline{B}\overline{C} \). Step 2: Group the first two terms and factor out \( A\overline{B} \) using the Distributive Law: \( A\overline{B}(\overline{C} + C) + \overline{A}B\overline{C} + \overline{A}\overline{B}\overline{C} \). Step 3: Simplify \( \overline{C} + C \) to 1 using the Complement (or Inverse) Law: \( A\overline{B}(1) + \overline{A}B\overline{C} + \overline{A}\overline{B}\overline{C} \). Step 4: Apply the Identity Law to obtain: \( A\overline{B} + \overline{A}B\overline{C} + \overline{A}\overline{B}\overline{C} \). Step 5: Group the remaining two terms and factor out \( \overline{A}\overline{C} \) using the Distributive Law: \( A\overline{B} + \overline{A}\overline{C}(B + \overline{B}) \). Step 6: Simplify \( B + \overline{B} \) to 1 using the Complement Law: \( A\overline{B} + \overline{A}\overline{C}(1) \). Step 7: Apply the Identity Law to obtain the final simplified expression: \( F = A\overline{B} + \overline{A}\overline{C} \).

評分準則

1 mark: Correctly factoring the first two terms: \( A\overline{B}(\overline{C} + C) \). 1 mark: Simplifying \( \overline{C} + C = 1 \) and \( A\overline{B} \cdot 1 = A\overline{B} \) with appropriate laws cited. 1 mark: Correctly factoring the third and fourth terms: \( \overline{A}\overline{C}(B + \overline{B}) \). 1 mark: Simplifying \( B + \overline{B} = 1 \) and \( \overline{A}\overline{C} \cdot 1 = \overline{A}\overline{C} \) with appropriate laws cited. 1 mark: Final correct simplified expression: \( F = A\overline{B} + \overline{A}\overline{C} \) (or equivalent). 2 marks: Correctly naming/identifying at least two laws used during the simplification (e.g., Distributive Law, Complement / Inverse Law, Identity Law). Award 1 mark if only one law is correctly named.
題目 10 · Short Answer
7.4
A client workstation requests a web page from a remote server over the Internet. The communication is managed using the TCP/IP protocol suite. Describe the roles of the Application, Transport, and Network (Internet) layers when sending this request from the client. For each of these three layers, state one protocol that operates at that layer during this interaction.
查看答案詳解

解題

At the Application Layer, the client web browser formats the request using a protocol such as HTTP or HTTPS. This creates the message payload. At the Transport Layer, the TCP protocol is used to establish a reliable connection with the server, break the application message into segments, and add TCP headers containing source and destination port numbers. At the Network (Internet) Layer, the IP protocol takes these segments and encapsulates them into IP packets by adding headers with the source and destination IP addresses, enabling routers to direct them across the Internet. Throughout this process, encapsulation occurs as each layer adds its own header to the data received from the layer above.

評分準則

Award up to 7 marks as follows. Application Layer (Max 2 marks): 1 mark for explaining the role (creates/formats the request) and 1 mark for identifying HTTP or HTTPS. Transport Layer (Max 2 marks): 1 mark for explaining the role (splits data, handles reliable end-to-end transmission, adds port numbers) and 1 mark for identifying TCP. Network Layer (Max 2 marks): 1 mark for explaining the role (adds IP addresses, routes packets) and 1 mark for identifying IP. Interaction (1 mark): 1 mark for explaining that data is passed down through these layers in sequence and encapsulated with headers at each stage.
題目 11 · Long Essay / Program Design
13
A local logistics company tracks its warehouse stock allocations using an unnormalised structure:

Warehouse(WarehouseID, WarehouseAddress, WarehouseCapacity, (ItemID, ItemDescription, ItemCategory, CategoryManager, QuantityStored))

Note: The nested parentheses indicate a repeating group of item details stored for each warehouse.

Write a design document addressing the following normalisation and database design tasks:

1. Explain how to bring this table into First Normal Form (1NF) and state the resulting relation(s). (2 marks)

2. Identify any partial key dependencies in your 1NF relations, explain how they violate Second Normal Form (2NF), and show the relations in 2NF. (4 marks)

3. Identify any transitive dependencies in your 2NF relations, explain how they violate Third Normal Form (3NF), and show the final database schema in 3NF. (4 marks)

4. Describe the relationships (e.g. 1:M) between your final 3NF tables and explain how referential integrity is maintained through foreign keys. (3 marks)
查看答案詳解

解題

Step-by-step Normalisation:

1. First Normal Form (1NF):
To eliminate the repeating groups of items, we flatten the relation. This results in a composite primary key consisting of WarehouseID and ItemID.
Relation:
StockAllocation(WarehouseID, ItemID, WarehouseAddress, WarehouseCapacity, ItemDescription, ItemCategory, CategoryManager, QuantityStored)
Primary Key: (WarehouseID, ItemID)

2. Second Normal Form (2NF):
To convert to 2NF, we must eliminate partial dependencies (where non-key attributes depend on only part of the composite primary key).
- WarehouseAddress and WarehouseCapacity depend only on WarehouseID.
- ItemDescription, ItemCategory, and CategoryManager depend only on ItemID.
- QuantityStored depends on both WarehouseID and ItemID.
Splitting these into separate tables yields:
- Warehouse(WarehouseID, WarehouseAddress, WarehouseCapacity) [PK: WarehouseID]
- Item(ItemID, ItemDescription, ItemCategory, CategoryManager) [PK: ItemID]
- Stock(WarehouseID, ItemID, QuantityStored) [PK: (WarehouseID, ItemID), FK: WarehouseID, ItemID]

3. Third Normal Form (3NF):
To convert to 3NF, we must eliminate transitive dependencies (where a non-key attribute depends on another non-key attribute).
In the Item table, CategoryManager depends on ItemCategory, which in turn depends on ItemID.
We extract this relationship into a new table:
- Category(ItemCategory, CategoryManager) [PK: ItemCategory]
- Item(ItemID, ItemDescription, ItemCategory) [PK: ItemID, FK: ItemCategory]
The other tables remain unchanged:
- Warehouse(WarehouseID, WarehouseAddress, WarehouseCapacity) [PK: WarehouseID]
- Stock(WarehouseID, ItemID, QuantityStored) [PK: (WarehouseID, ItemID), FK: WarehouseID, ItemID]

4. Relationships and Referential Integrity:
- Category to Item: 1-to-Many relationship (one category can have many items, but each item has one category). Link: ItemCategory.
- Item to Stock: 1-to-Many relationship (one item can be stored in many stock records). Link: ItemID.
- Warehouse to Stock: 1-to-Many relationship (one warehouse can hold many stock records). Link: WarehouseID.
Referential integrity ensures that a foreign key value (like WarehouseID in Stock) must match an actual primary key value in the parent table (Warehouse), preventing orphaned records and database inconsistency.

評分準則

Task 1 (1NF) [Max 2 marks]:
- 1 mark: Correct explanation of removing repeating groups / flattening the table.
- 1 mark: Correct 1NF relation: StockAllocation(WarehouseID, ItemID, WarehouseAddress, WarehouseCapacity, ItemDescription, ItemCategory, CategoryManager, QuantityStored) with composite PK underlined/indicated.

Task 2 (2NF) [Max 4 marks]:
- 1 mark: Clearly defining what a partial key dependency is.
- 1 mark: Correctly identifying the partial dependencies in this scenario (Warehouse details depend on WarehouseID; Item details depend on ItemID).
- 2 marks: Correct set of 2NF relations (1 mark if minor error, e.g., missing QuantityStored table or wrong PKs).

Task 3 (3NF) [Max 4 marks]:
- 1 mark: Clearly defining what a transitive dependency is (non-key attribute depends on another non-key attribute).
- 1 mark: Correctly identifying the transitive dependency in this scenario (ItemID -> ItemCategory -> CategoryManager).
- 2 marks: Correct set of 3NF relations (1 mark if minor error, e.g., forgot to make ItemCategory a FK in Item).

Task 4 (Relationships & Integrity) [Max 3 marks]:
- 1 mark: Correctly identifying the three 1:M relationships (Category-Item, Item-Stock, Warehouse-Stock).
- 1 mark: Clearly explaining the role of foreign keys in linking the tables.
- 1 mark: Correct definition of referential integrity (preventing orphaned records, ensuring every FK matches a valid PK).
題目 12 · Long Essay / Program Design
13
A large educational institution is designing its new campus network architecture. The network connects thousands of private client devices (laptops, lab PCs, and tablets) to the public Internet.

Write a technical report/essay addressing the following three key components of their network design:

1. Explain how a router uses its routing table to forward an IP packet from an internal client to an external web server. Your explanation should refer to the routing table structure, how the destination IP is processed, and how the next hop is determined. (4 marks)

2. Describe how Network Address Translation (NAT) operates to translate private IP addresses (e.g., 192.168.1.50) to a public IP address when a client requests a webpage, and how returning packets are routed back to the correct client. Explain why NAT is necessary in modern IPv4 networks. (5 marks)

3. Compare packet-filtering firewalls with stateful inspection firewalls, and recommend which of the two the institution should deploy at its boundary to protect the internal network. Justify your choice. (4 marks)
查看答案詳解

解題

1. Routing Table Packet Forwarding:
- A routing table contains destination network addresses, subnet masks, gateway/next hop IP addresses, and routing metrics (cost).
- When a packet arrives, the router inspects the packet header to extract the destination IP address.
- The router performs a bitwise AND operation on the destination IP with each subnet mask in the table.
- The resulting network address is compared against the destination network entries in the table. If a match is found, the packet is forwarded to the corresponding 'next hop' gateway or directly out of the associated network interface. If multiple matches exist, the longest prefix match (most specific route) is selected.

2. Network Address Translation (NAT):
- Private IP addresses (such as 192.168.X.X) are non-routable on the public Internet.
- When an internal device (e.g., 192.168.1.50) sends a packet to the Internet, it passes through the NAT-enabled boundary router.
- The router replaces the private source IP address and source port in the packet header with its own public IP address and a dynamically assigned unique source port.
- The router records this translation (Private IP & Port <-> Public IP & Unique Port) in its NAT translation table.
- When the web server replies, it sends the response to the router's public IP and the assigned port. The router performs a lookup in its NAT translation table to find the corresponding internal private IP and port, translates the destination headers back, and routes the packet to the correct internal client.
- NAT is essential because it mitigates IPv4 address exhaustion, allowing thousands of private devices to share a single public IP address, and adds security by concealing internal network layouts.

3. Firewalls (Packet-Filtering vs. Stateful Inspection):
- A packet-filtering firewall inspects individual packets in isolation. It compares packet header information (source/destination IP, source/destination port, protocol) against static rules (Access Control Lists) to decide whether to permit or deny the packet. It does not track connection state.
- A stateful inspection firewall monitors the state of active network connections (such as TCP handshakes and sequence numbers). It keeps a 'state table' of established sessions. Incoming packets are only permitted if they belong to an existing, legitimate outbound request or match explicit, secure rules.
- Recommendation: The institution must deploy a stateful inspection firewall.
- Justification: Packet filtering is vulnerable to IP spoofing and cannot dynamically handle complex protocols that use random high-numbered ports. Stateful inspection provides much greater security by blocking all unsolicited inbound connection attempts automatically while seamlessly allowing legitimate returning traffic.

評分準則

Part 1 (Routing) [Max 4 marks]:
- 1 mark: Explaining that a routing table contains destination networks, subnet masks, and next hops.
- 1 mark: Explaining that the router extracts the destination IP from incoming packets.
- 1 mark: Explaining the use of the subnet mask (bitwise AND) to find matching destination networks.
- 1 mark: Explaining how the packet is forwarded to the next hop or chosen interface (mentioning longest prefix match or metric for additional clarity).

Part 2 (NAT) [Max 5 marks]:
- 1 mark: Explaining that private IPs are non-routable and must be translated to a public IP to navigate the Internet.
- 1 mark: Explaining that the router modifies the packet header, replacing the private source IP and port with the public IP and a unique dynamic port.
- 1 mark: Explaining that the router logs this mapping in a NAT translation table.
- 1 mark: Explaining that incoming responses are mapped back to the correct private client using the translation table lookup.
- 1 mark: Explaining that NAT is essential to solve IPv4 address exhaustion or to add a layer of security by hiding internal structures.

Part 3 (Firewalls) [Max 4 marks]:
- 1 mark: Correctly defining packet-filtering firewalls (static rules, inspects packets individually in isolation).
- 1 mark: Correctly defining stateful inspection firewalls (tracks state of connections, maintains a state table).
- 1 mark: Making a clear recommendation for stateful inspection firewalls.
- 1 mark: Providing valid justification (e.g., prevents spoofing, blocks unsolicited incoming traffic, more secure than static filters).

想知道自己有幾分把握?

Thinka 是 DSE 學生用的 AI 練習應用程式,有無限量練習題、即時自動批改和詳細解題步驟。逾 100,000 名學生用它確認自己真的識,而不只是「以為識」。

想練更多類似題型?在 Thinka 無限量操練,即時知道答案。

免費開始練習