Cambridge IAL · Thinka 原創模擬試題

2025 Cambridge IAL Computer Science (9618) 模擬試題連答案詳解

Thinka Nov 2025 (V2) Cambridge International A Level-Style Mock — Computer Science (9618)

300 450 分鐘2025
An original Thinka practice paper modelled on the structure and difficulty of the Nov 2025 (V2) Cambridge International A Level Computer Science (9618) paper. Not affiliated with or reproduced from Cambridge.

Paper 12: Theory Fundamentals

Answer all questions. Calculators are not permitted. Show all working for mathematical computations.
9 題目 · 74
題目 1 · written
10
An online training agency manages its workshop bookings using a relational database. The database contains the following four tables:

`INSTRUCTOR(InstructorID, Name, Email, Specialism)`
`WORKSHOP(WorkshopID, Title, Date, Fee, InstructorID)`
`CUSTOMER(CustomerID, Name, Email)`
`BOOKING(BookingID, CustomerID, WorkshopID, PaymentStatus)`

(a) (i) Identify the Primary Key and any Foreign Keys in the `BOOKING` table. [2 marks]
(ii) State the relationship between the `WORKSHOP` table and the `BOOKING` table. [1 mark]

(b) Write an SQL DDL script to create the `WORKSHOP` table. Ensure that:
- `WorkshopID` is the primary key and must be a fixed-length string of 5 characters.
- `Title` is a variable-length string of up to 50 characters and cannot be null.
- `Fee` is a decimal number with up to 4 digits in total and 2 decimal places, defaulting to 0.00.
- `InstructorID` is a foreign key referencing the `INSTRUCTOR` table. [3 marks]

(c) Write an SQL query to display the `Name` and `Email` of all customers who have booked the workshop with the title `'Advanced Python'` and have a `PaymentStatus` of `'Pending'`. [4 marks]
查看答案詳解

解題

### Part (a)
(i) The `BOOKING` table is an associative entity designed to resolve a many-to-many relationship between `CUSTOMER` and `WORKSHOP`.
- **Primary Key**: `BookingID` uniquely identifies each record in this table.
- **Foreign Keys**: `CustomerID` (references `CUSTOMER`) and `WorkshopID` (references `WORKSHOP`) are required to link bookings to their respective customer and workshop records.

(ii) The relationship between `WORKSHOP` and `BOOKING` is **one-to-many** (or 1:M). One workshop can have multiple associated bookings, but each booking refers to exactly one workshop.

### Part (b)
To construct the DDL SQL statement for creating the `WORKSHOP` table:
- Define `WorkshopID` as a fixed-length string: `CHAR(5)` and declare it as the primary key.
- Define `Title` as a variable-length string: `VARCHAR(50)` and append `NOT NULL` to enforce that it cannot be left blank.
- Define `Fee` as `DECIMAL(4,2)` with the default constraint `DEFAULT 0.00`.
- Link the foreign key `InstructorID` to its parent table: `FOREIGN KEY (InstructorID) REFERENCES INSTRUCTOR(InstructorID)`.

```sql
CREATE TABLE WORKSHOP (
WorkshopID CHAR(5) PRIMARY KEY,
Title VARCHAR(50) NOT NULL,
Date DATE,
Fee DECIMAL(4,2) DEFAULT 0.00,
InstructorID VARCHAR(10),
FOREIGN KEY (InstructorID) REFERENCES INSTRUCTOR(InstructorID)
);
```
*(Note: Defining PRIMARY KEY on the column line or at the end of the script are both acceptable.)*

### Part (c)
To construct the SQL query:
1. Specify the output fields: `SELECT CUSTOMER.Name, CUSTOMER.Email` (or simply `Name, Email` if clear, but prefixing with table names is best practice).
2. Join the three necessary tables: `CUSTOMER`, `BOOKING`, and `WORKSHOP` using their relational keys.
3. Filter the records using the `WHERE` clause for both constraints: `Title = 'Advanced Python'` and `PaymentStatus = 'Pending'`.

```sql
SELECT CUSTOMER.Name, CUSTOMER.Email
FROM CUSTOMER
INNER JOIN BOOKING ON CUSTOMER.CustomerID = BOOKING.CustomerID
INNER JOIN WORKSHOP ON BOOKING.WorkshopID = WORKSHOP.WorkshopID
WHERE WORKSHOP.Title = 'Advanced Python'
AND BOOKING.PaymentStatus = 'Pending';
```

評分準則

### Part (a)
- **(i) [2 marks]**
- 1 mark for identifying `BookingID` as the Primary Key.
- 1 mark for identifying both `CustomerID` and `WorkshopID` as Foreign Keys (must name both for the mark).
- **(ii) [1 mark]**
- 1 mark for identifying the relationship as **one-to-many** (accept 1:M or 1 to many) from WORKSHOP to BOOKING.

### Part (b) [3 marks]
- **1 mark**: Correct creation statement with correct primary key definition (`WorkshopID CHAR(5)`).
- **1 mark**: Correct fields and data types for `Title` (`VARCHAR(50) NOT NULL`) and `Fee` (`DECIMAL(4,2) DEFAULT 0.00` or numeric equivalent).
- **1 mark**: Correct syntax for the foreign key specification: `FOREIGN KEY (InstructorID) REFERENCES INSTRUCTOR(InstructorID)`.

### Part (c) [4 marks]
- **1 mark**: Correct `SELECT` clause listing `Name` and `Email` (or `CUSTOMER.Name, CUSTOMER.Email`).
- **1 mark**: Correct `FROM` clause joining all three tables (`CUSTOMER`, `BOOKING`, `WORKSHOP`) via correct primary/foreign key pairs.
- **1 mark**: Correct logical query filter for `'Advanced Python'` text.
- **1 mark**: Correct logical query filter for `'Pending'` text combined with `AND`.

*Note for Part (c): Implicit joins in the WHERE clause are acceptable (e.g. FROM CUSTOMER, BOOKING, WORKSHOP WHERE CUSTOMER.CustomerID = BOOKING.CustomerID...)*
題目 2 · structured
12
A multi-story office building currently uses a legacy bus network topology. The network administrator has decided to upgrade the network infrastructure to a hybrid star-bus topology to improve performance and reliability.

(a) Describe the physical structure of a hybrid star-bus network topology, explaining how the components are interconnected. [4]

(b) The legacy bus network suffered from frequent packet collisions. The new hybrid network uses switches at the center of each star subnet. Explain how CSMA/CD operates in a network and why the transition to a switched star-bus network reduces the frequency of collisions. [4]

(c) The administrator also considered a full mesh topology. State two advantages and two disadvantages of choosing a hybrid star-bus topology instead of a full mesh topology for this multi-story building. [4]
查看答案詳解

解題

(a) Structure of hybrid star-bus:
- It consists of multiple star subnets connected together via a shared central bus backbone.
- Each individual star subnet has a central hub or switch to which individual computer systems (nodes) are directly connected via dedicated cables.
- The switches/hubs of each star network are then connected to a common bus line (backbone) to allow communication across different subnets.
- Terminators are present at the ends of the main bus backbone to prevent signal reflection.

(b) CSMA/CD and switched network:
- CSMA/CD (Carrier Sense Multiple Access with Collision Detection) works by devices listening to the communication channel (carrier sensing) before transmitting data. If the channel is clear, the device transmits.
- If two devices transmit at the same time, a collision occurs. The devices detect this collision, broadcast a jam signal, and wait a random duration of time before attempting to retransmit.
- In a switched star-bus network, switches create dedicated, point-to-point connection paths between sending and receiving devices, isolating traffic to specific ports rather than broadcasting to all segments.
- This divides the network into multiple collision domains, where each port on a switch is its own collision domain, vastly reducing or eliminating collisions compared to a shared bus medium.

(c) Advantages and disadvantages (compared to full mesh):
- Advantages:
1. Much lower cabling costs and easier installation as not every device needs a direct link to every other device.
2. Simpler to scale/expand by adding another star subnet to the bus backbone without disrupting the existing nodes.
- Disadvantages:
1. The bus backbone remains a single point of failure; if the main backbone cable breaks, communication between the star subnets is completely cut off.
2. Performance can degrade if heavy traffic is transmitted across the backbone, whereas a mesh network offers maximum throughput via direct routes.

評分準則

Part (a): [Max 4 marks]
- 1 mark for stating that multiple star subnets are connected via a central bus backbone.
- 1 mark for explaining individual nodes connect directly to a central hub/switch in a star layout.
- 1 mark for explaining that these hubs/switches connect directly to the bus backbone.
- 1 mark for mentioning terminators are needed at the ends of the backbone.

Part (b): [Max 4 marks]
- 1 mark for explaining CSMA/CD mechanism: device checks/listens if medium is free before sending.
- 1 mark for explaining collision response: if collision detected, devices stop, send jam signal, wait random time, then retry.
- 1 mark for explaining that a switch isolates traffic by sending data only to the destination port (point-to-point path).
- 1 mark for stating that this creates individual collision domains per port, preventing collisions.

Part (c): [Max 4 marks]
- 2 marks for advantages (1 mark per valid point, e.g., cheaper cabling, easier to expand/scale).
- 2 marks for disadvantages (1 mark per valid point, e.g., backbone is single point of failure, backbone bottleneck/lower redundancy compared to mesh).
題目 3 · structured
12
During data transmission across a network, errors can occur due to interference. Two methods of error detection are checksums and two-dimensional (block) parity.

(a) A system transmits four 8-bit data bytes. The system calculates an 8-bit checksum by adding the byte values together (ignoring any carry-out from the most significant bit) and then taking the two's complement of the result.

The four bytes of data are:
- Byte 1: 1011 0011
- Byte 2: 0110 1100
- Byte 3: 1100 1010
- Byte 4: 0011 1101

(i) Calculate the 8-bit sum of these four bytes, showing your working. [2]
(ii) Calculate the checksum byte to be transmitted. Show your working. [2]
(iii) Describe how the receiver uses the transmitted checksum to verify that the data has been received without error. [2]

(b) An alternative method is to use a block parity check (two-dimensional parity) with even parity. The four bytes are arranged in a grid with an extra parity bit added to the end of each row, and an extra parity byte (the column parity) added at the bottom.

(i) Copy and complete the table below to show the correct parity bits. [4]

Byte 1: 1 0 1 1 0 0 1 1 [Row Parity 1]
Byte 2: 0 1 1 0 1 1 0 0 [Row Parity 2]
Byte 3: 1 1 0 0 1 0 1 0 [Row Parity 3]
Byte 4: 0 0 1 1 1 1 0 1 [Row Parity 4]
Col Parity: [C1] [C2] [C3] [C4] [C5] [C6] [C7] [C8] [Block Parity]

(ii) Explain one limitation of a two-dimensional parity check. [2]
查看答案詳解

解題

(a)(i) 8-bit sum calculation:
- Step 1: \(10110011_{2} + 01101100_{2} = 00011111_{2}\) (carry discarded)
- Step 2: \(00011111_{2} + 11001010_{2} = 11101001_{2}\)
- Step 3: \(11101001_{2} + 00111101_{2} = 00100110_{2}\) (carry discarded)
- Final 8-bit sum = \(00100110_{2}\)

(a)(ii) Checksum byte calculation (two's complement of the sum):
- Step 1: Find one's complement of \(00100110_{2}\) -> \(11011001_{2}\)
- Step 2: Add 1 to find two's complement -> \(11011010_{2}\)
- Checksum byte = \(11011010_{2}\)

(a)(iii) Verification process:
- The receiver sums all four received data bytes and the received checksum byte using 8-bit addition (ignoring carry overflow).
- If the result is all zero bits (\(00000000_{2}\)), then no error is detected. If the result is non-zero, an error has occurred during transmission.

(b)(i) Completed parity grid:
- Row Parity 1: 1
- Row Parity 2: 0
- Row Parity 3: 0
- Row Parity 4: 1
- Column Parity bits:
- C1: 0
- C2: 0
- C3: 1
- C4: 0
- C5: 1
- C6: 0
- C7: 0
- C8: 0
- Block Parity: 0

(b)(ii) Limitation of 2D parity:
- If an even number of errors occurs in the exact same columns and rows (for example, a 4-bit error forming a rectangle in the grid), the parity checks will still appear correct, and the error will go undetected.

評分準則

Part (a)(i): [2 marks]
- 1 mark for showing correct binary addition steps (at least one intermediate step shown).
- 1 mark for correct final 8-bit sum: 00100110.

Part (a)(ii): [2 marks]
- 1 mark for demonstrating the process of two's complement (inverting bits and adding 1 to the sum calculated in part i).
- 1 mark for correct final checksum byte: 11011010.

Part (a)(iii): [2 marks]
- 1 mark for stating that receiver adds all received data bytes and the checksum byte.
- 1 mark for explaining that a result of all zeroes (00000000) indicates no error, while any other result indicates an error.

Part (b)(i): [4 marks]
- 1 mark for all four Row Parity bits correct (1, 0, 0, 1).
- 2 marks for all eight Column Parity bits correct (0, 0, 1, 0, 1, 0, 0, 0). Give 1 mark if 4 to 7 bits are correct.
- 1 mark for correct Block Parity bit (0).

Part (b)(ii): [2 marks]
- 1 mark for identifying that multiple/even errors can cancel each other out.
- 1 mark for explaining the specific condition (e.g., four errors forming a rectangle, or two errors in the same row and column).
題目 4 · Processor & Low Level Tracing
7
An assembly language program is to be traced. The table below shows a subset of the instruction set for the processor:

- LDM #n: Load immediate denary value n into ACC.
- LDD : Load contents of address into ACC.
- LDX : Load contents of (address + IX) into ACC.
- STO : Store contents of ACC into address.
- ADD : Add contents of address to ACC.
- INC : Increment contents of specified register (ACC or IX) by 1.
- TAX: Transfer contents of ACC to IX.
- TXA: Transfer contents of IX to ACC.
- CMP #n: Compare contents of ACC with immediate value n.
- JPN : Jump to address if comparison was NOT equal.
- END: Terminate execution.

Initial memory state:
- Address 100: 12
- Address 101: 5
- Address 102: 8
- Address 110: 99

Assembly program:
50: LDM #0
51: TAX
52: STO 110
53: LDX 100
54: ADD 110
55: STO 110
56: INC IX
57: TXA
58: CMP #3
59: JPN 53
60: END

Trace the program and state the final values of the Accumulator (ACC), Index Register (IX), and Memory Address 110 when the END instruction is reached.
查看答案詳解

解題

Step-by-step trace:

1. Instruction 50: ACC = 0
2. Instruction 51: IX = 0
3. Instruction 52: Memory[110] = 0

First Loop Iteration (IX = 0):
4. Instruction 53: ACC = Memory[100 + 0] = 12
5. Instruction 54: ACC = ACC + Memory[110] = 12 + 0 = 12
6. Instruction 55: Memory[110] = 12
7. Instruction 56: IX is incremented to 1
8. Instruction 57: ACC = IX = 1
9. Instruction 58: Compare 1 with 3 (Not equal)
10. Instruction 59: Jump to 53

Second Loop Iteration (IX = 1):
11. Instruction 53: ACC = Memory[100 + 1] = 5
12. Instruction 54: ACC = ACC + Memory[110] = 5 + 12 = 17
13. Instruction 55: Memory[110] = 17
14. Instruction 56: IX is incremented to 2
15. Instruction 57: ACC = IX = 2
16. Instruction 58: Compare 2 with 3 (Not equal)
17. Instruction 59: Jump to 53

Third Loop Iteration (IX = 2):
18. Instruction 53: ACC = Memory[100 + 2] = 8
19. Instruction 54: ACC = ACC + Memory[110] = 8 + 17 = 25
20. Instruction 55: Memory[110] = 25
21. Instruction 56: IX is incremented to 3
22. Instruction 57: ACC = IX = 3
23. Instruction 58: Compare 3 with 3 (Equal)
24. Instruction 59: Do not jump (comparison was equal)
25. Instruction 60: END

Final values:
- ACC: 3
- IX: 3
- Memory 110: 25

評分準則

Award up to 7 marks as follows:
- 1 mark for initializing ACC, IX to 0 and storing 0 in 110.
- 1 mark for the first loop execution (ACC loads 12, Memory 110 updated to 12).
- 1 mark for incrementing IX to 1 and copying to ACC.
- 1 mark for the second loop execution (ACC loads 5, Memory 110 updated to 17).
- 1 mark for incrementing IX to 2 and copying to ACC.
- 1 mark for the third loop execution (ACC loads 8, Memory 110 updated to 25).
- 1 mark for incrementing IX to 3, transferring to ACC, comparing, and terminating correctly with final values: ACC = 3, IX = 3, Memory 110 = 25.
題目 5 · Processor & Low Level Tracing
7
An assembly language program uses logical and bitwise instructions to inspect and process data.

Instruction subset:
- LDD : Load contents of address into ACC.
- LDM #n: Load immediate value n into ACC.
- AND #n: Bitwise AND of ACC with immediate value n.
- CMP #n: Compare contents of ACC with immediate value n.
- JPE : Jump to address if the comparison was equal.
- JMP : Jump to address.
- STO : Store contents of ACC into address.
- END: Terminate execution.

Consider the following program:
40: LDD 180
41: AND #4
42: CMP #4
43: JPE 47
44: LDM #0
45: STO 181
46: JMP 49
47: LDM #255
48: STO 181
49: END

(a) Trace the program when the initial content of address 180 is the denary value 22. State the final values of ACC and address 181. (4 marks)

(b) Trace the program when the initial content of address 180 is the denary value 17. State the final values of ACC and address 181. (3 marks)
查看答案詳解

解題

Detailed Tracing:

Part (a) with Input 22:
1. Instruction 40: ACC is loaded with the content of address 180, which is 22 (binary 0001 0110).
2. Instruction 41: ACC = 22 AND 4.
0001 0110 (22)
AND
0000 0100 (4)
= 0000 0100 (4 in denary).
ACC is now 4.
3. Instruction 42: Compare ACC (4) with immediate value 4. The comparison evaluates to Equal.
4. Instruction 43: Since comparison was equal, jump to instruction 47.
5. Instruction 47: Load immediate value 255 into ACC (ACC = 255).
6. Instruction 48: Store ACC (255) into address 181. Memory[181] = 255.
7. Instruction 49: END. Program halts.
Final state: ACC = 255, Memory[181] = 255.

Part (b) with Input 17:
1. Instruction 40: ACC is loaded with the content of address 180, which is 17 (binary 0001 0001).
2. Instruction 41: ACC = 17 AND 4.
0001 0001 (17)
AND
0000 0100 (4)
= 0000 0000 (0 in denary).
ACC is now 0.
3. Instruction 42: Compare ACC (0) with immediate value 4. The comparison evaluates to Not Equal.
4. Instruction 43: Since comparison was not equal, do not jump. Proceed to 44.
5. Instruction 44: Load immediate value 0 into ACC (ACC = 0).
6. Instruction 45: Store ACC (0) into address 181. Memory[181] = 0.
7. Instruction 46: Jump to instruction 49.
8. Instruction 49: END. Program halts.
Final state: ACC = 0, Memory[181] = 0.

評分準則

Award up to 7 marks as follows:

Part (a) [4 marks]:
- 1 mark: Correctly loading ACC with 22 and applying AND #4 to yield ACC = 4.
- 1 mark: Correctly identifying that 4 CMP 4 is true/equal.
- 1 mark: Correctly jumping to address 47 and loading 255 into ACC.
- 1 mark: Correctly storing 255 in address 181 and terminating.

Part (b) [3 marks]:
- 1 mark: Correctly loading ACC with 17 and applying AND #4 to yield ACC = 0.
- 1 mark: Correctly determining that 0 CMP 4 is false/not equal and avoiding the jump.
- 1 mark: Correctly executing instructions 44-46 to store 0 in address 181 and jumping to 49 to terminate.
題目 6 · Ethics & System Properties
6.5
A software engineer working for a major online retailer is instructed by their manager to implement a tracking script. This script will secretly record users' cursor movements and keystrokes on partner websites to build behavioral profiles for targeted advertising, without obtaining user consent or disclosing this practice in the privacy policy. (a) Explain how this instruction violates three distinct ethical principles of a professional code of conduct, such as the ACM/IEEE Software Engineering Code of Ethics. [3 marks] (b) The engineer decides to resign and instead develop an alternative open-source privacy-focused analytics tool. Describe the difference between licensing this tool under the GNU General Public License (GPL) versus a proprietary commercial license, with explicit reference to the 'four essential freedoms' defined by the Free Software Foundation. [3.5 marks]
查看答案詳解

解題

(a) 1. PUBLIC: Software engineers shall act consistently with the public interest. Secret tracking without consent harms user privacy and trust, violating this interest. 2. CLIENT AND EMPLOYER: Software engineers shall act in a manner that is in the best interests of their client and employer, consistent with the public interest. While the manager ordered it, the public interest override makes secret tracking unethical. 3. PRODUCT: Software engineers shall ensure that their products meet the highest professional standards possible. Incorporating covert spyware features degrades the integrity and quality of the product. (b) The GNU GPL is a copyleft license that ensures users have the 'four essential freedoms': the freedom to run the program, study/change the source code, redistribute copies, and distribute modified versions. It requires any modified versions to also be open-source under the GPL. A proprietary license restricts these freedoms: users cannot access, modify, or distribute the source code, and use is governed by restrictive terms of service.

評分準則

Part (a) [3 marks]: - 1 mark per valid explanation of a violation mapped to an ethical principle from a professional code of conduct (such as ACM/IEEE or BCS), up to a maximum of 3 marks. (Acceptable principles include: Public, Client and Employer, Product, Judgment, Management, Profession, Colleagues, Self). Part (b) [3.5 marks]: - 1 mark for defining GNU GPL as copyleft / requiring derived works to remain open. - 1 mark for outlining at least two of the 'four freedoms' (run, study/modify, redistribute, distribute modified versions). - 1 mark for explaining proprietary software restrictions (no access to source code, restricted distribution). - 0.5 marks for clear comparative contrast between the two models.
題目 7 · Ethics & System Properties
6.5
A financial technology company deploys an Artificial Neural Network (ANN) to evaluate and automatically approve or reject personal loan applications. (a) Describe two ethical challenges specifically associated with using a 'black box' ANN model for automated financial decision-making. [3 marks] (b) Explain how the system designers can implement 'algorithmic transparency' and 'fairness' during the training and validation phases of this machine learning system to mitigate these ethical challenges. [3.5 marks]
查看答案詳解

解題

(a) 1. Lack of Explainability (Black Box Problem): ANNs have hidden layers with complex weights that make it difficult or impossible to explain to a rejected applicant exactly why their application was denied, violating the ethical right to explanation. 2. Bias and Discrimination: If the historical training data contains human biases (e.g., historical redlining or gender bias), the ANN will learn and amplify these biases, leading to unfair systemic discrimination. (b) Algorithmic Transparency can be implemented by using explainable AI (XAI) tools (e.g., feature importance analysis) or auditing the neural network's decision boundaries. Fairness can be implemented by carefully auditing and pre-processing the training dataset to remove biased attributes (such as gender, race, or postal codes associated with specific demographics) and verifying that the validation accuracy is equal across different demographic subgroups.

評分準則

Part (a) [3 marks]: - 1.5 marks for describing the black box/explainability problem (1 mark for identifying the issue, 0.5 marks for explaining it in the context of loan rejection). - 1.5 marks for describing bias/discrimination (1 mark for identifying training data bias, 0.5 marks for explaining its amplification in automated decisions). Part (b) [3.5 marks]: - 1.5 marks for explaining how to implement Algorithmic Transparency (e.g., post-hoc explanation models, feature analysis, auditing inputs/outputs). - 1.5 marks for explaining how to implement Fairness (e.g., cleansing/balancing training data, removing proxy variables, ensuring demographic parity during validation). - 0.5 marks for linking both mitigation strategies directly to the training/validation phase.
題目 8 · Ethics & System Properties
6.5
A regional health clinic maintains a local database storing sensitive electronic health records (EHR) of patients. (a) Identify and describe three distinct methods or controls that the clinic can implement to maintain the integrity of data during data entry and daily operations. [3 marks] (b) Distinguish between data privacy and data security in the context of this clinic, providing one distinct technical measure the clinic must implement for each. [3.5 marks]
查看答案詳解

解題

(a) 1. Validation Rules: Implementing range checks, format checks, or presence checks on input fields (e.g., verifying blood pressure values are within reasonable physical limits) to prevent incorrect data from being entered. 2. Verification: Double entry of key fields (such as patient ID) or visual verification by staff before committing changes to ensure the data entered matches the source document. 3. Database Constraints / Referential Integrity: Ensuring foreign keys match primary keys (e.g., preventing a prescription from being linked to a non-existent patient ID) to maintain logical consistency. (b) Data security refers to the protective measures used to safeguard data from unauthorized access, corruption, or theft (e.g., implementing AES-256 encryption on hard drives or using firewalls). Data privacy refers to the appropriate use, collection, and legal handling of data, ensuring individuals have control over their personal information (e.g., establishing access control lists so only authorized medical practitioners can view specific patient medical histories, or implementing patient consent management systems).

評分準則

Part (a) [3 marks]: - 1 mark for each valid method/control to maintain data integrity (max 3). Examples: Input validation (must specify a type like range/format check), Verification (e.g., double entry/visual check), Referential integrity/Database constraints, Audit trails. Part (b) [3.5 marks]: - 1 mark for a clear definition of data security (protection against unauthorized access/loss/corruption). - 1 mark for a clear definition of data privacy (appropriate/legal use, user consent, who has authorized access). - 1 mark for providing one correct technical measure for security (e.g., firewalls, encryption, physical locks). - 0.5 marks for providing one correct technical measure/policy implementation for privacy (e.g., role-based access control, consent logging, data minimization).
題目 9 · Ethics & System Properties
6.5
A major logistics warehouse is planning to replace its manual inventory sorting staff with an automated robotic sorting system guided by computer vision algorithms. (a) Discuss two distinct social impacts and two distinct ethical concerns of introducing this automated system on the displaced workforce and the wider local community. [4 marks] (b) The server farm powering these computer vision algorithms requires substantial electrical energy. Describe one hardware-level practice and one software-level practice the company can adopt to minimize the environmental impact of running this system. [2.5 marks]
查看答案詳解

解題

(a) Social Impacts: 1. Unemployment and job displacement: Warehouse workers may lose their livelihoods, leading to financial hardship and economic strain on the local community. 2. Skills gap / Digital divide: Displaced workers may struggle to find new jobs because they lack the high-tech skills required to operate or maintain robotic systems, widening the inequality gap. Ethical Concerns: 1. Corporate Responsibility / Duty of Care: Does the company have an ethical obligation to retrain workers or provide fair severance, rather than simply prioritizing profits? 2. Algorithmic bias and safety: If the robotic vision system misidentifies objects or humans, it could pose physical safety hazards to remaining floor workers, raising issues of liability and safety ethics. (b) Hardware-level practice: Deploying energy-efficient processors (such as ARM-based chips or TPUs optimized for AI workloads) that have lower thermal design power (TDP), or sourcing power from renewable energy (solar/wind panels on the warehouse roof). Software-level practice: Optimizing the computer vision code by pruning the neural network (reducing parameter counts), or scheduling intensive batch computing tasks to run during off-peak hours when the local grid relies more heavily on renewable energy sources.

評分準則

Part (a) [4 marks]: - 1 mark per valid social impact discussed (max 2). Acceptable: Job losses, local economic decline, need for retraining, deskilling. - 1 mark per valid ethical concern discussed (max 2). Acceptable: Corporate responsibility for employee welfare, safety/liability of autonomous systems, deskilling as an ethical issue, unequal distribution of tech benefits. Part (b) [2.5 marks]: - 1 mark for a valid hardware-level practice (e.g., energy-efficient processors/TPUs, server virtualization to maximize server utilization, using renewable energy sources, energy-efficient cooling systems). - 1 mark for a valid software-level practice (e.g., model pruning/quantization to reduce computational overhead, algorithmic optimization to reduce Big-O complexity, scheduling tasks for off-peak hours). - 0.5 marks for clear and logical technical justification of how the chosen practice reduces environmental impact (e.g., reducing e-waste or carbon footprint).

Paper 22: Algorithmic Logic & Pseudocode

Write all answers in correct pseudocode as detailed in the index booklet. Maintain strict variable scoping rules.
8 題目 · 80
題目 1 · Modular Pseudocode Design
14
An airline booking system represents a row of 30 passenger seats using a 1D array of Booleans named SeatRow, indexed from 1 to 30. A value of TRUE indicates the seat is reserved, and FALSE indicates the seat is empty. Write pseudocode for a function MaxEmptySeats that takes this array as a parameter and returns the maximum number of consecutive empty seats available in that row. Declare all local variables used inside the function.
查看答案詳解

解題

The function starts by initializing MaxCount and CurrentCount to 0. A FOR loop iterates from index 1 to 30. Inside the loop, we check if SeatRow[Index] is FALSE. If true, we increment CurrentCount by 1 and check if it exceeds MaxCount, updating MaxCount if necessary. If SeatRow[Index] is TRUE, the sequence of consecutive empty seats is broken, so we reset CurrentCount to 0. After the loop, the function returns MaxCount.

評分準則

1 mark: Correct FUNCTION header with parameter and RETURNS INTEGER. 2 marks: Correct DECLARE statements for all local variables with correct data types. 2 marks: Proper initialization of MaxCount and CurrentCount to 0. 2 marks: Correct FOR loop from 1 to 30. 2 marks: Correct check for FALSE value and increment of CurrentCount. 2 marks: Correct comparison and update of MaxCount. 1 mark: Correct resetting of CurrentCount to 0 in ELSE block. 1 mark: Correct RETURN statement and ENDFUNCTION.
題目 2 · Modular Pseudocode Design
14
A system validates an employee ID code. A valid ID code must be a string of exactly 7 characters in the format 'LL-DDDD', where 'L' represents an uppercase alphabetical character (A to Z) and 'D' represents a numeric character (0 to 9). Write pseudocode for a function ValidateID that takes a string input parameter InputID and returns TRUE if it is valid, and FALSE otherwise. You must use built-in string manipulation functions such as LENGTH(Str) and MID(Str, Start, Length). Declare all local variables used inside the function.
查看答案詳解

解題

First, the length of InputID is verified using LENGTH(InputID). If it is not exactly 7, FALSE is returned immediately. A loop processes characters at index 1 and 2, ensuring they are uppercase letters between 'A' and 'Z'. Next, the character at index 3 is checked to ensure it is a hyphen '-'. Finally, another loop validates that characters at indices 4 to 7 are numeric characters between '0' and '9'. If all validation checks pass, the function returns TRUE.

評分準則

1 mark: Correct FUNCTION header and return type BOOLEAN. 2 marks: Correct DECLARE statements for local variables. 2 marks: Correctly checking that length is 7 using LENGTH(). 2 marks: Loop and conditional check for the first two uppercase alphabetic characters. 2 marks: Checking third character is a hyphen. 2 marks: Loop and conditional check for digits 0 to 9 at indices 4 to 7. 2 marks: Correctly returning TRUE if all checks pass, returning FALSE otherwise, and ENDFUNCTION.
題目 3 · Modular Pseudocode Design
14
A garden center tracks plant inventory using a record structure. Define a record structure named Plant containing fields Species (a string), Price (a real number), and InStock (an integer). Write pseudocode for a procedure FilterLowStock that takes two parameters: an array StockArray of 100 Plant records, and an integer parameter Threshold. The procedure must loop through the array, output the Species and Price of each plant whose InStock level is less than or equal to Threshold, and display a final count of all such low-stock plants. Declare all local variables.
查看答案詳解

解題

First, the record structure Plant is defined with Species, Price, and InStock fields. The procedure FilterLowStock is declared with two parameters. A local variable Count is initialized to 0. A FOR loop iterates from 1 to 100 to check each plant record. If the InStock field of the current plant is less than or equal to Threshold, its Species and Price are printed, and Count is incremented. After the loop, the total count is displayed.

評分準則

2 marks: Defining TYPE Plant record structure with correct field names and types. 1 mark: Correct PROCEDURE header with array parameter and integer Threshold parameter. 2 marks: Declaring Index and Count as local variables of type INTEGER. 1 mark: Initializing Count to 0. 2 marks: Loop correctly scanning array from 1 to 100. 2 marks: Correct conditional check using record array dot notation (StockArray[Index].InStock <= Threshold). 2 marks: Outputting Species and Price fields of the matching record. 1 mark: Incrementing Count and displaying final count after loop. 1 mark: Correct ENDPROCEDURE and no return values used.
題目 4 · open-ended
11
An environmental monitoring station records sensor readings as an array of 50 strings. Each string is formatted as a 3-letter ID, followed by a colon (':'), followed by a numeric reading (for example, 'TMP:23.5' or 'HUM:62.0'). Write a pseudocode procedure, ProcessSensorData, which takes an array of 50 strings, Readings, as a parameter. The procedure must perform the following tasks: 1. Loop through all 50 readings. 2. Extract the ID and the value substring. 3. Check if the ID is 'TMP' (Temperature) or 'HUM' (Humidity). If not, output 'ERROR: Invalid ID' and increment an error counter. 4. If the ID is valid, convert the value substring to a REAL data type using the built-in function STR_TO_REAL. 5. Validate the converted real value: if the ID is 'TMP', it must be between -10.0 and 50.0 inclusive; if the ID is 'HUM', it must be between 0.0 and 100.0 inclusive. If the value is out of bounds, output 'ERROR: Out of bounds' and increment the error counter. 6. If the reading is valid, accumulate totals to calculate average values later. 7. After the loop, output the average 'TMP' value (if at least one valid 'TMP' reading exists, otherwise 'No valid TMP readings'), the average 'HUM' value (if at least one valid 'HUM' reading exists, otherwise 'No valid HUM readings'), and the total count of errors. Note: Semicolons are used in the solution to represent line breaks.
查看答案詳解

解題

PROCEDURE ProcessSensorData(Readings : ARRAY OF STRING); DECLARE i, TmpCount, HumCount, ErrorCount : INTEGER; DECLARE CurrentReading, ID, ValueStr : STRING; DECLARE ValueReal, TmpTotal, HumTotal : REAL; TmpTotal <- 0.0; HumTotal <- 0.0; TmpCount <- 0; HumCount <- 0; ErrorCount <- 0; FOR i <- 1 TO 50; CurrentReading <- Readings[i]; ID <- LEFT(CurrentReading, 3); ValueStr <- MID(CurrentReading, 5, LENGTH(CurrentReading) - 4); IF ID = "TMP" THEN; ValueReal <- STR_TO_REAL(ValueStr); IF ValueReal >= -10.0 AND ValueReal <= 50.0 THEN; TmpTotal <- TmpTotal + ValueReal; TmpCount <- TmpCount + 1; ELSE; OUTPUT "ERROR: Out of bounds"; ErrorCount <- ErrorCount + 1; ENDIF; ELSE; IF ID = "HUM" THEN; ValueReal <- STR_TO_REAL(ValueStr); IF ValueReal >= 0.0 AND ValueReal <= 100.0 THEN; HumTotal <- HumTotal + ValueReal; HumCount <- HumCount + 1; ELSE; OUTPUT "ERROR: Out of bounds"; ErrorCount <- ErrorCount + 1; ENDIF; ELSE; OUTPUT "ERROR: Invalid ID"; ErrorCount <- ErrorCount + 1; ENDIF; ENDIF; NEXT i; IF TmpCount > 0 THEN; OUTPUT "Average TMP: ", TmpTotal / TmpCount; ELSE; OUTPUT "No valid TMP readings"; ENDIF; IF HumCount > 0 THEN; OUTPUT "Average HUM: ", HumTotal / HumCount; ELSE; OUTPUT "No valid HUM readings"; ENDIF; OUTPUT "Total errors: ", ErrorCount; ENDPROCEDURE

評分準則

Total: 11 marks. 1 mark: Correct PROCEDURE header with array parameter. 1 mark: Declaration of all variables with appropriate types. 1 mark: Correct loop from 1 to 50. 2 marks: Correctly extracting ID using LEFT(..., 3) and ValueStr using MID(..., 5, LENGTH(...) - 4) (or equivalent logic). 1 mark: Validating ID as 'TMP' or 'HUM', outputting error and incrementing ErrorCount if invalid. 2 marks: Validating TMP value range (-10.0 to 50.0) and HUM value range (0.0 to 100.0), handling bounds errors. 1 mark: Correctly casting string to real using STR_TO_REAL. 1 mark: Accumulating totals and incrementing counts for valid TMP and HUM readings. 1 mark: Correctly calculating and outputting average TMP, average HUM (handling division by zero check), and final total error count.
題目 5 · open-ended
11
A software system validates registration keys represented as strings. A valid key has the format 'XXXX-YYYY-Z' where XXXX and YYYY are 4-digit numeric substrings, and Z is a single-digit verification check. Write a pseudocode function, ValidateSerialNumber, which takes a string, SerialKey, as a parameter and returns a BOOLEAN value. The function must perform the following tasks: 1. Validate that the overall length of SerialKey is exactly 11. 2. Verify that hyphens are located at indices 5 and 10. 3. Extract substrings for Part1 (characters 1 to 4), Part2 (characters 6 to 9), and Part3 (character 11). 4. Check every character in Part1, Part2, and Part3 to ensure it is a numeric digit ('0' to '9'). If not, output 'Key verification failed' and return FALSE. 5. Cast Part1, Part2, and Part3 to integers using the built-in function STR_TO_NUM. 6. Check if (Part1_integer + Part2_integer) MOD 9 is equal to Part3_integer. 7. If valid, output 'Key accepted. Sum: ' concatenated with the string representation of (Part1_integer + Part2_integer) using the built-in function NUM_TO_STR, and return TRUE. 8. If invalid, output 'Key verification failed' and return FALSE. Note: Semicolons are used in the solution to represent line breaks.
查看答案詳解

解題

FUNCTION ValidateSerialNumber(SerialKey : STRING) RETURNS BOOLEAN; DECLARE Part1, Part2, Part3, ChStr : STRING; DECLARE Val1, Val2, Val3, i, Sum : INTEGER; IF LENGTH(SerialKey) <> 11 THEN; OUTPUT "Key verification failed"; RETURN FALSE; ENDIF; IF MID(SerialKey, 5, 1) <> "-" OR MID(SerialKey, 10, 1) <> "-" THEN; OUTPUT "Key verification failed"; RETURN FALSE; ENDIF; Part1 <- MID(SerialKey, 1, 4); Part2 <- MID(SerialKey, 6, 4); Part3 <- MID(SerialKey, 11, 1); FOR i <- 1 TO 4; ChStr <- MID(Part1, i, 1); IF ChStr < "0" OR ChStr > "9" THEN; OUTPUT "Key verification failed"; RETURN FALSE; ENDIF; NEXT i; FOR i <- 1 TO 4; ChStr <- MID(Part2, i, 1); IF ChStr < "0" OR ChStr > "9" THEN; OUTPUT "Key verification failed"; RETURN FALSE; ENDIF; NEXT i; ChStr <- MID(Part3, 1, 1); IF ChStr < "0" OR ChStr > "9" THEN; OUTPUT "Key verification failed"; RETURN FALSE; ENDIF; Val1 <- STR_TO_NUM(Part1); Val2 <- STR_TO_NUM(Part2); Val3 <- STR_TO_NUM(Part3); IF (Val1 + Val2) MOD 9 = Val3 THEN; Sum <- Val1 + Val2; OUTPUT "Key accepted. Sum: " & NUM_TO_STR(Sum); RETURN TRUE; ELSE; OUTPUT "Key verification failed"; RETURN FALSE; ENDIF; ENDFUNCTION

評分準則

Total: 11 marks. 1 mark: Correct FUNCTION header with parameter and RETURNS BOOLEAN. 1 mark: Check for overall string length of 11. 1 mark: Verification of hyphens at indices 5 and 10. 1 mark: Correctly extracting Part1, Part2, and Part3 using MID. 2 marks: Loop and conditional logic to verify each character in Part1, Part2, and Part3 is between '0' and '9'. 2 marks: Correct type casting of all three substrings to integers using STR_TO_NUM. 1 mark: Performing modular arithmetic correctly using MOD. 1 mark: Casting the sum back to a string using NUM_TO_STR and concatenating with the accepted message. 1 mark: Correct return of TRUE and FALSE paths with matching user outputs.
題目 6 · Flowchart Translation
5
A programmer has designed an algorithm to calculate the average of a series of positive numbers entered by a user. The input is terminated by the sentinel value -999.

The following textual description represents the flowchart of the algorithm:
1. Start.
2. Set Sum to 0, set Count to 0.
3. Input Value.
4. Is Value equal to -999?
- If YES, go to step 8.
- If NO, go to step 5.
5. Is Value greater than 0?
- If YES, add Value to Sum, and add 1 to Count.
- If NO, go to step 7.
6. Go to step 7.
7. Input Value and go back to step 4.
8. Is Count greater than 0?
- If YES, calculate Average = Sum / Count, output Average.
- If NO, output "No data".
9. Stop.

Write the pseudocode that matches this flowchart, adhering to the standard CIE 9618 pseudocode rules.
查看答案詳解

解題

To translate the flowchart steps into correct CIE 9618 pseudocode:
1. First, initialize variables: `Sum <- 0` and `Count <- 0`.
2. Perform the initial `INPUT Value` before entering the loop.
3. Implement a `WHILE` loop with the condition `Value <> -999` to repeatedly check for the sentinel value.
4. Inside the loop, use an `IF` statement to check if `Value > 0`. If true, update `Sum` and `Count`.
5. Read the next input `INPUT Value` inside the loop before the loop ends to allow the condition to be re-evaluated.
6. After the loop terminates, check `IF Count > 0` to prevent division by zero.
7. If `Count > 0`, calculate `Average <- Sum / Count` and output the result. Otherwise, output "No data".

評分準則

Marks are awarded as follows:
- 1 Mark: Correct initialization of `Sum` and `Count` to 0, and initial `INPUT Value` outside the loop.
- 1 Mark: Correct loop structure (`WHILE Value <> -999 DO` / `ENDWHILE` or equivalent `REPEAT...UNTIL`).
- 1 Mark: Correct selection structure inside the loop (`IF Value > 0 THEN`) updating `Sum` and `Count` correctly.
- 1 Mark: Correct position of the secondary `INPUT Value` statement before the end of the loop structure.
- 1 Mark: Correct post-loop conditional check (`IF Count > 0 THEN`) to prevent division by zero, with correct output of average or "No data".
題目 7 · written
5.5
A structure chart is being designed for a banking application module `ProcessTransaction`.

The main module `ProcessTransaction` calls three modules: `ValidateCard`, `CheckBalance`, and `DispenseCash`.
- `ValidateCard` receives `CardNumber` and returns a boolean `CardValid`.
- `CheckBalance` is only called if `CardValid` is TRUE. It receives `CardNumber` and returns the `AccountBalance`.
- `DispenseCash` is called if `AccountBalance` is sufficient. It receives the `WithdrawalAmount` and returns a transaction status code `Status`.

(a) State the name of the parameter(s) passed as a control couple in this system. [1]
(b) Identify which module is executed conditionally, and explain how this is represented on a structure chart. [2]
(c) Explain the difference between a data couple and a control couple in a structure chart. [1.5]
(d) State the purpose of a curved arrow (arc) across the connection lines in a structure chart. [1]
查看答案詳解

解題

(a) The control couple is CardValid because it contains a boolean state flag used by the calling module to make a decision on whether to execute other modules.
(b) CheckBalance or DispenseCash are executed conditionally. On a structure chart, conditional calling of modules is shown using a selection symbol (a small unfilled diamond) placed at the point where the connector lines leave the parent module.
(c) A data couple is used to move data values between modules for processing and is symbolized by an arrow with an open circle. A control couple is used to pass a flag or signal that governs the program logic/flow and is symbolized by an arrow with a filled-in circle.
(d) A loop or iteration is denoted on a structure chart by drawing a curved arrow across the line(s) connecting the parent module to the repeated child module(s).

評分準則

(a) [1 Mark]
- 1 mark for identifying 'CardValid' (accept 'Status' if justified as controlling execution flow, but 'CardValid' is primary).

(b) [2 Marks]
- 1 mark for identifying 'CheckBalance' or 'DispenseCash'.
- 1 mark for stating it is represented by a diamond symbol on the connection line/junction.

(c) [1.5 Marks]
- 1 mark for contrasting the data representation (data couple = open circle arrow, control couple = filled circle arrow).
- 0.5 marks for defining their function (data couple passes processing values, control couple passes flags/conditions to control logic flow).

(d) [1 Mark]
- 1 mark for stating it represents iteration / repetition of a module call.
題目 8 · written
5.5
An educational institution is upgrading its Student Management System using the Software Development Life Cycle (SDLC).

(a) Compare the 'Analysis' stage and the 'Design' stage of the SDLC by stating one specific activity and one specific deliverable (output) for each stage. [3]
(b) During the 'Maintenance' stage of the SDLC, updates and modifications are made. Name and describe two distinct types of testing that must be conducted during maintenance to ensure system stability. [2.5]
查看答案詳解

解題

(a) During Analysis, developers investigate the existing system and user needs. Typical activities include interviews, surveys, or document analysis. The output is a Requirements Specification. During Design, developers plan the technical architecture. Activities include drawing flowcharts, entity-relationship diagrams, and pseudocode. The output is a Design Specification (containing user interface, database, and program designs). Analysis is problem-oriented (what to solve), and Design is solution-oriented (how to build it).
(b) Maintenance requires targeted testing:
- Regression Testing: Critical to ensure that any modification (corrective or perfective) has not introduced new bugs into existing modules that worked previously.
- Integration Testing: Ensures that the updated module integrates correctly with existing APIs, data layers, or modules without communication breakdown.

評分準則

(a) [3 Marks total]
- 1 mark for correct Analysis activity (e.g., interviewing, observation, questionnaires) AND deliverable (e.g., Requirements Specification, Feasibility Study).
- 1 mark for correct Design activity (e.g., creating structure charts, ERDs, interface wireframes) AND deliverable (e.g., design specification, program specifications).
- 1 mark for clear comparison of purpose (Analysis focus on understanding requirements / "what"; Design focus on structural planning / "how").

(b) [2.5 Marks total]
- 1 mark for naming and explaining Regression testing (tests existing parts to ensure updates didn't break them).
- 1 mark for naming and explaining Integration testing (tests connections between the new/modified parts and the old system) [Accept: Alpha/Beta/User Acceptance testing if description correctly matches maintenance validation].
- 0.5 marks for clearly explaining the context of stability during maintenance.

Paper 32: Advanced Systems & Machine Learning

Demonstrate understanding of complex networking, computational logic, operating systems and AI architectures.
10 題目 · 67.5
題目 1 · Recursion, Exception & Stack Tracing
8.5
An algorithm is written to process recursive state evaluations in an A Level Computer Science syllabus. Study the following pseudocode function:

```pseudocode
FUNCTION Evaluate(X : INTEGER, Y : INTEGER) RETURNS INTEGER
IF X <= 0 OR Y <= 0 THEN
RETURN 1
ELSEIF X > Y THEN
RETURN Evaluate(X - Y, Y) + X
ELSE
RETURN Evaluate(X, Y - X) * Y
ENDIF
ENDFUNCTION
```

(a) Trace the execution of the call `Evaluate(3, 5)`. Show each recursive call step, the parameters passed, and the final evaluated return value. [4.5]

(b) Explain the role of a stack frame (activation record) during these recursive calls, specifying three items of data stored within each frame. [3]

(c) State the runtime error that occurs if a recursive function fails to reach its base case, and explain why this happens in terms of system memory. [1]
查看答案詳解

解題

(a) Tracing steps:
- Call 1: `Evaluate(3, 5)` -> since 3 <= 5, returns `Evaluate(3, 2) * 5`
- Call 2: `Evaluate(3, 2)` -> since 3 > 2, returns `Evaluate(1, 2) + 3`
- Call 3: `Evaluate(1, 2)` -> since 1 <= 2, returns `Evaluate(1, 1) * 2`
- Call 4: `Evaluate(1, 1)` -> since 1 <= 1, returns `Evaluate(1, 0) * 1`
- Call 5: `Evaluate(1, 0)` -> Y is 0 (which is <= 0), returns 1.

Unwinding the call stack:
- Call 5 returns 1.
- Call 4 returns 1 * 1 = 1.
- Call 3 returns 1 * 2 = 2.
- Call 2 returns 2 + 3 = 5.
- Call 1 returns 5 * 5 = 25.

(b) Role of Stack Frame:
Each time a function is called, a stack frame is pushed onto the call stack to maintain the execution state of that active subroutine. It is popped when the subroutine terminates.
Three items stored in each frame:
1. Return address (the program instruction pointer indicating where to resume execution in the calling routine)
2. Parameters passed to the subroutine (the values of X and Y)
3. Local variables declared inside the subroutine.

(c) Runtime Error:
Stack Overflow. This occurs because every recursive call allocates a new stack frame on the call stack. Without reaching a base case, infinite recursion occurs, which completely exhausts the finite memory allocated for the call stack.

評分準則

Part (a): 4.5 marks total
- 0.5 marks for each correct recursive call step with correct arguments (Calls 2, 3, 4, 5) [Max 2 marks]
- 0.5 marks for identifying Call 5 returns 1 [0.5 marks]
- 1.0 mark for correct unwinding trace showing correct intermediate return values [1 mark]
- 1.0 mark for correct final answer of 25 [1 mark]

Part (b): 3.0 marks total
- 1.0 mark for explaining the role of a stack frame (maintaining state of active subroutine calls)
- 2.0 marks for listing 3 correct items of data (e.g., return address, parameters, local variables) (0.5 marks each, rounded up to 2)

Part (c): 1.0 mark total
- 0.5 marks for identifying 'Stack Overflow'
- 0.5 marks for explaining it as exhaustion of stack memory due to unlimited creation of stack frames.
題目 2 · Recursion, Exception & Stack Tracing
8.5
Consider the following pseudocode program containing nested subroutine calls with custom exception handling blocks:

```pseudocode
01 PROCEDURE Alpha()
02 TRY
03 OUTPUT "Alpha Start"
04 Beta()
05 OUTPUT "Alpha End"
06 EXCEPT DivisionByZero
07 OUTPUT "Alpha Handled DivZero"
08 EXCEPT OutOfBounds
09 OUTPUT "Alpha Handled OutOfBounds"
10 ENDTRY
11 ENDPROCEDURE
12
13 PROCEDURE Beta()
14 TRY
15 OUTPUT "Beta Start"
16 Gamma(0)
17 OUTPUT "Beta End"
18 EXCEPT FileError
19 OUTPUT "Beta Handled File"
20 ENDTRY
21 ENDPROCEDURE
22
23 PROCEDURE Gamma(X : INTEGER)
24 DECLARE Arr : ARRAY[0..2] OF INTEGER
25 TRY
26 OUTPUT "Gamma Start"
27 IF X = 0 THEN
28 Arr[5] <- 100
29 ELSE
30 X <- 10 / X
31 ENDIF
32 OUTPUT "Gamma End"
33 EXCEPT DivisionByZero
34 OUTPUT "Gamma Handled DivZero"
35 ENDTRY
36 ENDPROCEDURE
```

(a) Trace and write the complete, sequential console output when `Alpha()` is called. [3]

(b) Describe what happens to the call stack and active memory records during exception propagation from `Gamma` back to `Alpha` when the error is raised. [3.5]

(c) State two fundamental differences in control flow between throwing an exception and executing a standard subroutine return statement. [2]
查看答案詳解

解題

(a) Sequential Console Output:
1. Alpha Start
2. Beta Start
3. Gamma Start
4. Alpha Handled OutOfBounds

(b) Call Stack Unwinding Details:
- At line 28 in `Gamma`, execution of `Arr[5] <- 100` throws an `OutOfBounds` exception because array index 5 is out of bounds (declared as 0..2).
- The normal execution of `Gamma` is immediately suspended. The runtime engine searches the local `TRY...EXCEPT` block for an `OutOfBounds` handler. Since only `DivisionByZero` is handled locally, the exception cannot be caught here.
- The call stack frame for `Gamma` is popped (discarded) from the stack, and local variables/memory allocated to `Gamma` are deallocated. The exception propagates up to `Beta`.
- In `Beta`, execution is suspended at line 16. The runtime engine searches `Beta`'s local exceptions for a handler. Only `FileError` is defined, so the exception remains uncaught. `Beta`'s stack frame is popped from the stack.
- The exception propagates to `Alpha`. In `Alpha`, execution is suspended at line 04. The handler `EXCEPT OutOfBounds` matches the exception. Execution jumps directly to line 09, outputting "Alpha Handled OutOfBounds". Alpha's stack frame remains active and executes normally after the exception block.

(c) Differences in Control Flow:
1. Standard return statements transfer control directly back to the instruction immediately following the call in the immediate caller. In contrast, exceptions can propagate upward across multiple levels of the call stack (unwinding) until a matching handler is found.
2. A return statement successfully concludes a subroutine's normal logic and can return a computed value. An exception abnormally interrupts and aborts execution, bypassing subsequent subroutine code and preventing a normal value from being returned.

評分準則

Part (a): 3.0 marks total
- 1.0 mark for correct first three outputs in order ("Alpha Start", "Beta Start", "Gamma Start").
- 1.0 mark for omitting "Gamma End" and "Beta End" from the output.
- 1.0 mark for the final output "Alpha Handled OutOfBounds".

Part (b): 3.5 marks total
- 1.0 mark for identifying that execution of the current scope (`Gamma`) immediately halts and does not complete normal termination.
- 1.0 mark for describing the removal/popping of stack frames (`Gamma` then `Beta`) from the call stack (unwinding).
- 1.0 mark for explaining that propagation continues upward through the calling chain until a matching exception block is located.
- 0.5 marks for specifying that the exception is resolved in `Alpha`'s handler block, allowing `Alpha` to exit gracefully.

Part (c): 2.0 marks total
- 1.0 mark for stating that standard return resumes immediately after the calling statement, whereas exceptions bypass levels of the stack.
- 1.0 mark for stating that return completes subroutine execution normally with/without a value, whereas throwing aborts the subroutine and transfers control to handling routines.
題目 3 · Recursion, Exception & Stack Tracing
8.5
In an artificial intelligence pathfinding routine, a recursive depth-limited node evaluator is implemented as shown below:

```pseudocode
FUNCTION NodeValue(Depth : INTEGER, Score : INTEGER) RETURNS INTEGER
OUTPUT "Enter depth ", Depth
IF Depth >= 3 THEN
OUTPUT "Base node reached"
RETURN Score + 10
ELSE
IF Depth MOD 2 = 0 THEN
Score <- NodeValue(Depth + 1, Score * 2)
ELSE
Score <- NodeValue(Depth + 2, Score + 5) + NodeValue(Depth + 1, Score)
ENDIF
ENDIF
OUTPUT "Exit depth ", Depth, " with ", Score
RETURN Score
ENDFUNCTION
```

(a) Write down the exact, line-by-line output generated when the call `NodeValue(0, 3)` is executed. [5]

(b) Identify the maximum number of activation records (stack frames) that reside on the stack simultaneously during this entire execution (excluding the main calling environment). Justify your selection. [2]

(c) Explain how passing the `Score` parameter *by reference* (instead of *by value*) would alter the output and state of the stack frames. [1.5]
查看答案詳解

解題

(a) Output Sequence Trace:
1. `Enter depth 0`
2. `Enter depth 1`
3. `Enter depth 3`
4. `Base node reached`
5. `Enter depth 2`
6. `Enter depth 3`
7. `Base node reached`
8. `Exit depth 2 with 22`
9. `Exit depth 1 with 43`
10. `Exit depth 0 with 43`

Detailed Trace Breakdown:
- `NodeValue(0, 3)` enters. Outputs "Enter depth 0". Since 0 MOD 2 = 0 is True, calls `NodeValue(1, 6)`.
- `NodeValue(1, 6)` enters. Outputs "Enter depth 1". Since 1 MOD 2 = 0 is False, initiates addition: left side calls `NodeValue(3, 11)`.
- `NodeValue(3, 11)` enters. Outputs "Enter depth 3" and "Base node reached". Returns 21.
- In `NodeValue(1, 6)`, the left operand is now 21. It now evaluates the right operand of addition: `NodeValue(2, 6)` (with original local `Score` = 6).
- `NodeValue(2, 6)` enters. Outputs "Enter depth 2". Since 2 MOD 2 = 0 is True, calls `NodeValue(3, 12)`.
- `NodeValue(3, 12)` enters. Outputs "Enter depth 3" and "Base node reached". Returns 22.
- In `NodeValue(2, 6)`, `Score` is updated to 22. Outputs "Exit depth 2 with 22". Returns 22.
- In `NodeValue(1, 6)`, the right operand returns 22. Score becomes `21 + 22 = 43`. Outputs "Exit depth 1 with 43". Returns 43.
- In `NodeValue(0, 3)`, Score is updated to 43. Outputs "Exit depth 0 with 43". Returns 43.

(b) Maximum Stack Frames:
- The maximum number of simultaneously active stack frames is 4.
- This occurs during the right branch when the call stack contains: `NodeValue(0, 3)` -> `NodeValue(1, 6)` -> `NodeValue(2, 6)` -> `NodeValue(3, 12)`.

(c) Passing by Reference vs. Value:
- Currently, parameters are passed by value, meaning each stack frame has its own independent copy of `Score` stored locally on the stack frame.
- If passed by reference, all frames would point to the same memory location for `Score`. A modification to `Score` in a deeper call (such as `Score <- NodeValue(...)`) would immediately alter the variable in the caller's frame. For instance, when the left recursive call `NodeValue(3, 11)` runs, any side-effect change would overwrite the caller's `Score` variable, meaning subsequent calls like `NodeValue(2, Score)` would receive incorrect modified values instead of the original local copy.

評分準則

Part (a): 5.0 marks total
- 1.5 marks for correctly tracing the initial depth entries up to the first base case ("Enter depth 0", "Enter depth 1", "Enter depth 3", "Base node reached").
- 1.5 marks for correctly tracing the right branch entry ("Enter depth 2", "Enter depth 3", "Base node reached").
- 1.0 mark for correct intermediate returns and output values ("Exit depth 2 with 22", "Exit depth 1 with 43").
- 1.0 mark for correct final output ("Exit depth 0 with 43").

Part (b): 2.0 marks total
- 1.0 mark for stating '4' stack frames.
- 1.0 mark for correct justification pointing out the chain of active calls: `NodeValue(0,3)` -> `NodeValue(1,6)` -> `NodeValue(2,6)` -> `NodeValue(3,12)`.

Part (c): 1.5 marks total
- 0.5 marks for stating that passing by reference uses pointers to a single memory location rather than local copies.
- 1.0 mark for explaining that changes to `Score` in child stack frames would overwrite/alter `Score` in parent stack frames, distorting subsequent calculations (such as passing a mutated `Score` to the right-hand recursive call instead of the original value).
題目 4 · written
9
A system designer is developing a digital logic circuit that processes a 4-bit input binary value representing \(A, B, C, D\), where \(A\) is the Most Significant Bit (MSB) and \(D\) is the Least Significant Bit (LSB).

The Boolean function \(X\) is defined by the following sum-of-products (SOP) expression:

\[X = \bar{A}\bar{B}\bar{C}\bar{D} + \bar{A}\bar{B}C\bar{D} + \bar{A}B\bar{C}\bar{D} + \bar{A}BC\bar{D} + AB\bar{C}\bar{D} + AB\bar{C}D + ABC\bar{D} + ABCD\]

(a) Complete the following Karnaugh Map (K-map) for the Boolean expression \(X\) by filling in all the cells with 1s and 0s. [4 marks]

```
CD | 00 | 01 | 11 | 10
AB----+----+----+----+----
00 | | | |
01 | | | |
11 | | | |
10 | | | |
```

(b) Draw loop(s) on your completed K-map in Part (a) to show the groupings of 1s that result in the minimum number of terms. [2 marks]

(c) Using your loops from Part (b), write the simplified sum-of-products Boolean expression for \(X\). [1 mark]

(d) Describe or draw the simplified logic circuit for \(X\) using standard logic gates. [2 marks]
查看答案詳解

解題

Part (a):
The terms in the expression map to the following coordinates in the K-map (as row AB, col CD):
- \(\bar{A}\bar{B}\bar{C}\bar{D}\) -> (00, 00) = 1
- \(\bar{A}\bar{B}C\bar{D}\) -> (00, 10) = 1
- \(\bar{A}B\bar{C}\bar{D}\) -> (01, 00) = 1
- \(\bar{A}BC\bar{D}\) -> (01, 10) = 1
- \(AB\bar{C}\bar{D}\) -> (11, 00) = 1
- \(AB\bar{C}D\) -> (11, 01) = 1
- \(ABC\bar{D}\) -> (11, 10) = 1
- \(ABCD\) -> (11, 11) = 1
All other cells are 0.

Completed K-map:
```
CD | 00 | 01 | 11 | 10
AB----+----+----+----+----
00 | 1 | 0 | 0 | 1
01 | 1 | 0 | 0 | 1
11 | 1 | 1 | 1 | 1
10 | 0 | 0 | 0 | 0
```

Part (b):
We identify two groups of 4 cells to cover all 1s:
1. A horizontal loop of size 4 containing the entire row \(AB = 11\).
2. A loop of size 4 containing the four cells in columns \(CD = 00\) and \(CD = 10\), across rows \(AB = 00\) and \(AB = 01\). This is a adjacent-column block wrapping group representing \(\bar{A}\bar{D}\).

Part (c):
- The horizontal group (row 11) simplifies to: \(AB\)
- The vertical wrapping group simplifies to: \(\bar{A}\bar{D}\)
Simplified Boolean Expression: \(X = AB + \bar{A}\bar{D}\)

Part (d):
To construct the circuit:
- Pass input \(A\) through a NOT gate to obtain \(\bar{A}\).
- Pass input \(D\) through a NOT gate to obtain \(\bar{D}\).
- Connect \(A\) and \(B\) to the inputs of a 2-input AND gate (produces \(AB\)).
- Connect \(\bar{A}\) and \(\bar{D}\) to the inputs of another 2-input AND gate (produces \(\bar{A}\bar{D}\)).
- Connect the outputs of both AND gates to the inputs of a 2-input OR gate to produce the final output \(X\).

評分準則

Part (a) [4 marks]:
- 1 mark for correct K-map row and column headings in Gray code order (00, 01, 11, 10).
- 3 marks for all 1s and 0s placed correctly. (Award 2 marks if 1 or 2 entries are incorrect; award 1 mark if 3 or 4 entries are incorrect; 0 marks otherwise).

Part (b) [2 marks]:
- 1 mark for drawing a loop around the entire row of 1s (\(AB = 11\)).
- 1 mark for drawing a loop around the 4-cell group spanning columns \(CD = 00, 10\) and rows \(AB = 00, 01\).

Part (c) [1 mark]:
- 1 mark for the correct simplified expression: \(X = AB + \bar{A}\bar{D}\) (Accept equivalent logical notations like \(AB + A'D'\) or \(A \cdot B + \text{NOT}(A) \cdot \text{NOT}(D)\)).

Part (d) [2 marks]:
- 1 mark for two correctly configured AND terms (one with inputs \(A\) and \(B\); one with inverted inputs \(A\) and \(D\)).
- 1 mark for a final OR gate combining both AND terms into the final output \(X\).
題目 5 · descriptive
5
Alice wants to send a confidential document to Bob over an insecure network. She also wants Bob to be able to verify that the document definitely came from her and has not been altered during transmission. Explain how digital signatures and asymmetric key cryptography are used together by Alice and Bob to achieve both confidentiality and non-repudiation.
查看答案詳解

解題

1. Alice generates a message digest (hash) of the document using a cryptographic hashing algorithm (e.g., SHA-256). 2. Alice encrypts this message digest using her private key to create the digital signature. This ensures non-repudiation and authenticity. 3. Alice then encrypts both the original document and the digital signature using Bob's public key. This ensures confidentiality since only Bob can decrypt it. 4. Bob receives the ciphertext and decrypts it using his private key to recover the document and the digital signature. 5. Bob decrypts the digital signature using Alice's public key to retrieve the original message digest. He also hashes the decrypted document independently and compares his computed hash with the decrypted digest. If they match, authenticity and integrity are verified.

評分準則

Award 1 mark for each of the following points, up to a maximum of 5 marks: 1 mark: Alice hashes the original document to create a message digest. 1 mark: Alice encrypts the hash/digest with her own private key to create the digital signature (authenticity/non-repudiation). 1 mark: Alice encrypts the document and signature with Bob's public key (confidentiality). 1 mark: Bob decrypts the package using his private key. 1 mark: Bob decrypts the signature with Alice's public key to extract the original hash, hashes the received document, and compares the two hashes (integrity/verification).
題目 6 · descriptive
5
When a web browser establishes a secure connection to an e-commerce website, it initiates a Transport Layer Security (TLS) handshake. Describe the sequence of steps that occur during this handshake to securely negotiate session keys between the client and the server.
查看答案詳解

解題

1. The client sends a 'Client Hello' message to the server containing its supported TLS version, cipher suites, and a random byte string. 2. The server responds with a 'Server Hello' message, choosing the cipher suite, and sends its SSL/TLS digital certificate containing the server's public key along with another random byte string. 3. The client verifies the validity of the server's digital certificate using the pre-installed public keys of trusted Certificate Authorities (CAs). 4. The client generates a random pre-master secret, encrypts it using the server's public key, and sends it back to the server. 5. The server decrypts the pre-master secret using its private key. Both the client and server then use the pre-master secret and the exchanged random byte strings to compute the same symmetric session key. They exchange 'Finished' messages encrypted with this session key to complete the handshake.

評分準則

Award 1 mark for each of the following points, up to a maximum of 5 marks: 1 mark: Client sends Client Hello with TLS version, cipher suites, and a random string. 1 mark: Server responds with Server Hello and sends its digital certificate containing its public key. 1 mark: Client validates the server's certificate against trusted Certificate Authorities (CAs). 1 mark: Client generates a pre-master secret, encrypts it with the server's public key, and sends it to the server (or uses Diffie-Hellman key exchange). 1 mark: Both parties use the shared secret to generate identical symmetric session keys, then send finished messages to confirm secure communication.
題目 7 · descriptive
5
The BitTorrent protocol is a widely used peer-to-peer (P2P) protocol for distributing large amounts of data. Explain how a BitTorrent client downloads a file, detailing the specific roles of the torrent file, the tracker, and the swarm (comprising seeders and leechers). Address how file integrity is maintained during this process.
查看答案詳解

解題

1. The user obtains a .torrent file which contains essential metadata about the files to be shared, including piece sizes, SHA-1 cryptographic hashes for each piece, and the URL of one or more trackers. 2. The client contacts the tracker server, which acts as a central coordinator, maintaining a list of active peers currently sharing the file (the swarm) and returning their IP addresses to the client. 3. The client connects directly to these peers. Seeders are peers who possess the complete file and only upload pieces. Leechers are peers who are currently downloading the file and simultaneously uploading pieces they have already acquired. 4. The file is requested and downloaded in small, non-sequential pieces from multiple peers concurrently, which increases transfer speeds and reduces bottlenecks. 5. As each piece is received, the client computes its cryptographic hash and compares it to the corresponding SHA-1 hash stored in the .torrent file to ensure that the piece has not been corrupted or tampered with.

評分準則

Award 1 mark for each of the following points, up to a maximum of 5 marks: 1 mark: Explaining that the torrent file contains metadata, tracker URLs, and cryptographic hashes of individual file pieces. 1 mark: Explaining the role of the tracker as a central server that maintains the list of peers (the swarm) and helps them connect. 1 mark: Defining seeders (possess 100% of the file and upload) and leechers (possess parts of the file and download/upload simultaneously). 1 mark: Explaining that the file is split into pieces and downloaded concurrently/non-sequentially from multiple peers. 1 mark: Explaining how file integrity is verified by hashing each downloaded piece and comparing it to the hashes in the torrent file.
題目 8 · written
6
A real binary number is represented in normalized floating-point format with a 10-bit mantissa and a 6-bit exponent, both in two's complement.

(a) Convert the following floating-point representation into its denary equivalent. Show your working.

Mantissa: `0110100000`
Exponent: `000101`

(b) Describe the effect on the range and precision of numbers that can be represented if the format is altered to use an 8-bit mantissa and an 8-bit exponent.
查看答案詳解

解題

(a)
1. Exponent is `000101` which is positive. In denary, this is \(1 \times 2^2 + 1 \times 2^0 = 5\).
2. Mantissa is `0110100000`. With the binary point after the first bit (sign bit), it is `0.110100000`.
3. Converting mantissa to denary: \(0.5 + 0.25 + 0.0625 = 0.8125\).
4. Multiply the mantissa by \(2^{\text{exponent}}\):
\(0.8125 \times 2^5 = 0.8125 \times 32 = 26\).

(b)
1. The precision of the represented numbers decreases because there are fewer bits (from 10 to 8) allocated to the mantissa, reducing the number of significant digits.
2. The range of the represented numbers increases because more bits (from 6 to 8) are allocated to the exponent, allowing for much larger positive exponents and much smaller negative exponents (closer to zero).

評分準則

Part (a) [Max 3 marks]:
- 1 mark for calculating the correct exponent value (5).
- 1 mark for calculating the correct mantissa value (0.8125 or 13/16).
- 1 mark for calculating the correct final denary value (26) with working.

Part (b) [Max 3 marks]:
- 1 mark for stating that precision decreases because of fewer mantissa bits.
- 1 mark for stating that range increases because of more exponent bits.
- 1 mark for explaining the link (e.g., fewer bits in mantissa means larger step size/less detail; more bits in exponent means larger maximum and smaller minimum values can be represented).
題目 9 · written
6
Deep learning models rely heavily on Artificial Neural Networks (ANNs) for processing data and making predictions.

(a) Explain the purpose of an activation function in a neuron, and explain why a non-linear activation function is preferred over a linear one. (3 marks)

(b) Describe the role of backpropagation during the training phase of a deep neural network. (3 marks)
查看答案詳解

解題

(a)
1. Purpose: An activation function determines whether a neuron should fire/be activated by taking the weighted sum of its inputs plus a bias and mapping it to an output range.
2. Non-linear preference: Without a non-linear activation function, the entire network would collapse into a linear combination, making it no more powerful than a single-layer linear model (incapable of learning complex decision boundaries).
3. Non-linear activation functions (like ReLU or Sigmoid) allow the network to approximate any arbitrary, complex non-linear relationship within the training data.

(b)
1. Backpropagation is used to calculate the gradient of the loss function with respect to each weight in the network.
2. It works backward through the layers from the output to the input, using the chain rule of calculus to compute the error contributions at each node.
3. The calculated gradients are then passed to an optimization algorithm (such as gradient descent) which adjusts the weights and biases to minimize the total loss/error.

評分準則

Part (a) [Max 3 marks]:
- 1 mark: Explain the basic purpose (maps weighted sum + bias to output, determines if neuron fires).
- 1 mark: State that a linear network is equivalent to a single layer / cannot learn non-linear patterns.
- 1 mark: State that non-linear functions allow the network to learn complex/arbitrary features and non-linear relationships.

Part (b) [Max 3 marks]:
- 1 mark: Mentions calculating the gradient of the loss/error function.
- 1 mark: Explains the direction (working backward from output to input) using the chain rule.
- 1 mark: Explains that these gradients are used to update weights/biases (via gradient descent) to minimize error.
題目 10 · written
6
Two normalized floating-point numbers are represented using an 8-bit mantissa and a 4-bit exponent, both in two's complement.

Number A: Mantissa = `01100000`, Exponent = `0011`
Number B: Mantissa = `01010000`, Exponent = `0010`

(a) Show the steps required to add these two numbers. Provide your final sum in normalized floating-point format. Show your working. (4 marks)

(b) Explain how floating-point underflow can occur during a mathematical calculation. (2 marks)
查看答案詳解

解題

(a)
Step 1: Identify that the exponents are different. Exponent A = `0011` (3), Exponent B = `0010` (2). We align the exponents to the larger one (3).
Step 2: Adjust Number B to match exponent 3. Shift its mantissa right by 1 bit and increment its exponent.
Adjusted B Mantissa = `00101000` (value \(0.0101_2\)), Adjusted B Exponent = `0011` (3).
Step 3: Add the mantissas:
`01100000` (A) + `00101000` (B) = `10001000` (which is 1.0001000 in binary, indicating a carry out of the mantissa because the addition of two positive numbers has resulted in a sign bit of 1).
Step 4: Normalize the sum. Since there was a carry/overflow of the mantissa, we shift the mantissa right by 1 place and increment the exponent by 1.
Normalized Mantissa = `01000100`
Normalized Exponent = `0011` + 1 = `0100` (4).

(b)
1. Floating-point underflow occurs when the absolute value of a calculated non-zero result is too small to be represented by the format.
2. This happens when the negative exponent required to represent the number is more negative than the minimum possible exponent value allowed by the number of bits allocated to the exponent.

評分準則

Part (a) [Max 4 marks]:
- 1 mark: Identify exponents are different and select the larger exponent (3) as the target.
- 1 mark: Correctly shift B's mantissa to `00101000` to align with exponent 3.
- 1 mark: Add mantissas correctly to get `10001000` (or 1.0001000).
- 1 mark: Normalize the result correctly to get Mantissa = `01000100` and Exponent = `0100`.

Part (b) [Max 2 marks]:
- 1 mark: Define underflow as a non-zero value being too small/close to zero to be represented.
- 1 mark: Explain that it happens because the required negative exponent exceeds the limit of the exponent's bit width (more negative than the minimum representable exponent).

Paper 42: Practical Coding Environment

Implement solutions in Java, Python or Visual Basic console modes. Take screenshots of exact running test instances.
3 題目 · 75
題目 1 · practical
28
An international logistics company manages deliveries using an object-oriented programming solution.

Your task is to design, implement, and test two classes, `Package` and `ExpressPackage`, and write a program to manage them.

### Part (a)
Create a class `Package` with the following requirements:
* Private attributes:
* `PackageID` (String) - unique identifier
* `Weight` (Real/Float) - package weight in kilograms
* `Destination` (String) - destination city
* `BaseCost` (Real/Float) - the minimum base shipping fee
* A constructor that takes all four attributes as parameters and initializes them.
* Getters for all four attributes.
* A public method `CalculateCost()` that returns the total delivery cost as a Real/Float, calculated as:
$$\text{Total Cost} = \text{BaseCost} + (\text{Weight} \times 1.5)$$

Write the class definition for `Package` using your chosen language (Python, Java, or VB.NET).

[8 Marks]

---

### Part (b)
Create a class `ExpressPackage` that inherits from `Package`.
* Private attributes:
* `IsNextDay` (Boolean) - whether express delivery is overnight
* `ExpressFee` (Real/Float) - flat surcharge for rapid handling
* A constructor that takes all parameters for `Package`, plus `IsNextDay` and `ExpressFee`, and initializes them. Ensure the base class constructor is properly called.
* Getters for the new attributes.
* A public method `CalculateCost()` that overrides the parent method. It must calculate the cost as follows:
* If `IsNextDay` is `True`, the cost is: $$\text{Parent Cost} + (\text{ExpressFee} \times 1.5)$$
* If `IsNextDay` is `False`, the cost is: $$\text{Parent Cost} + \text{ExpressFee}$$

Write the class definition for `ExpressPackage` using your chosen language.

[6 Marks]

---

### Part (c)
Create a text file named `packages.txt` containing the following data:
```text
STANDARD,PKG001,4.5,London,12.00
EXPRESS,PKG002,2.0,Paris,15.00,TRUE,10.00
STANDARD,PKG003,10.2,New York,25.00
EXPRESS,PKG004,1.5,Tokyo,18.00,FALSE,8.00
STANDARD,PKG005,5.0,Sydney,30.00
```
In your main program, declare a 1D array or list named `PackageList` that can hold up to 10 `Package` objects.

Write a procedure `ReadData()` that:
1. Opens and reads `packages.txt` line by line.
2. Splices or splits each line by commas.
3. Instantiates either a `Package` or `ExpressPackage` object depending on the first token (`STANDARD` or `EXPRESS`).
4. Stores each instantiated object in `PackageList`.
5. Handles file-handling errors securely using exception handling.

Write the code for `ReadData()` and the instantiation of `PackageList`.

[8 Marks]

---

### Part (d)
Write a main function/routine that:
1. Calls `ReadData()` to populate `PackageList`.
2. Prompts the user to input a package ID to search.
3. Performs a linear search on `PackageList` to find the target ID.
4. If found, displays the package's destination, its calculated cost, and details of its type (Standard or Express).
5. If not found, outputs an appropriate "Not Found" message.

Test your program by running it and searching for:
* `PKG002`
* `PKG999` (non-existent)

Take screenshots of your program's outputs for both search tests.

[6 Marks]
查看答案詳解

解題

### Python 3 Solution

```python
# Part (a)
class Package:
def __init__(self, package_id, weight, destination, base_cost):
self.__PackageID = str(package_id)
self.__Weight = float(weight)
self.__Destination = str(destination)
self.__BaseCost = float(base_cost)

def get_package_id(self):
return self.__PackageID

def get_weight(self):
return self.__Weight

def get_destination(self):
return self.__Destination

def get_base_cost(self):
return self.__BaseCost

def CalculateCost(self):
return self.__BaseCost + (self.__Weight * 1.5)

# Part (b)
class ExpressPackage(Package):
def __init__(self, package_id, weight, destination, base_cost, is_next_day, express_fee):
super().__init__(package_id, weight, destination, base_cost)
self.__IsNextDay = bool(is_next_day)
self.__ExpressFee = float(express_fee)

def get_is_next_day(self):
return self.__IsNextDay

def get_express_fee(self):
return self.__ExpressFee

def CalculateCost(self):
parent_cost = super().CalculateCost()
if self.__IsNextDay:
return parent_cost + (self.__ExpressFee * 1.5)
else:
return parent_cost + self.__ExpressFee

# Part (c)
PackageList = []

def ReadData():
global PackageList
try:
file = open("packages.txt", "r")
for line in file:
line = line.strip()
if not line:
continue
parts = line.split(",")
pkg_type = parts[0]
pkg_id = parts[1]
weight = float(parts[2])
dest = parts[3]
base_cost = float(parts[4])

if pkg_type == "STANDARD":
new_pkg = Package(pkg_id, weight, dest, base_cost)
PackageList.append(new_pkg)
elif pkg_type == "EXPRESS":
is_next_day = True if parts[5].upper() == "TRUE" else False
express_fee = float(parts[6])
new_pkg = ExpressPackage(pkg_id, weight, dest, base_cost, is_next_day, express_fee)
PackageList.append(new_pkg)
file.close()
print("Data loaded successfully.")
except FileNotFoundError:
print("Error: The file packages.txt was not found.")
except Exception as e:
print("An error occurred:", str(e))

# Part (d) Main Routine
def main():
ReadData()
search_id = input("Enter Package ID to search: ").strip()
found = False

for pkg in PackageList:
if pkg.get_package_id() == search_id:
found = True
dest = pkg.get_destination()
cost = pkg.CalculateCost()
if isinstance(pkg, ExpressPackage):
pkg_type = "Express"
else:
pkg_type = "Standard"
print(f"Package found!")
print(f"Type: {pkg_type}")
print(f"Destination: {dest}")
print(f"Total Cost: ${cost:.2f}")
break

if not found:
print("Package not found.")

if __name__ == "__main__":
main()
```

---

### Sample Test Outputs (Python)

**Test Case 1 (PKG002):**
```text
Data loaded successfully.
Enter Package ID to search: PKG002
Package found!
Type: Express
Destination: Paris
Total Cost: $33.00
```
*(Calculation: Base cost 15.00 + (2.0 * 1.5) = 18.00. Express Fee 10.00 * 1.5 = 15.00. Total = 18.00 + 15.00 = 33.00)*

**Test Case 2 (PKG999):**
```text
Data loaded successfully.
Enter Package ID to search: PKG999
Package not found.
```

評分準則

### Part (a) [Total: 8 Marks]
* **1 Mark**: Correct declaration of class `Package` header.
* **1 Mark**: Private attributes declared correctly (e.g. `__` in Python or private visibility modifiers in Java/VB).
* **2 Marks**: Constructor correctly written accepting and setting all 4 fields (attributes).
* **2 Marks**: All getter methods correctly written.
* **2 Marks**: Method `CalculateCost()` correctly calculates and returns `BaseCost + (Weight * 1.5)`.

### Part (b) [Total: 6 Marks]
* **1 Mark**: Correct inheritance declaration showing `ExpressPackage` is a subclass of `Package`.
* **1 Mark**: Correct constructor declaration accepting parent and subclass attributes.
* **1 Mark**: Base class constructor correctly called with arguments (`super()` or equivalent).
* **1 Mark**: Subclass attributes correctly stored as private.
* **2 Marks**: Method `CalculateCost()` overrides parent method correctly, utilizing standard pricing calculation when `IsNextDay` is true/false.

### Part (c) [Total: 8 Marks]
* **1 Mark**: `PackageList` declared globally/globally accessible as an array or list of 10 maximum capacity.
* **1 Mark**: File open operation inside structured `try-catch` / `try-except` block.
* **1 Mark**: File closed appropriately (or using context managers like `with`).
* **1 Mark**: Reading from file line-by-line.
* **1 Mark**: Correct splitting of attributes with commas.
* **1 Mark**: Logic to determine subclass or superclass dynamically based on record type.
* **2 Marks**: Instantiating objects correctly with parsed data types (e.g., parsing strings to floats/booleans) and adding them to `PackageList`.

### Part (d) [Total: 6 Marks]
* **1 Mark**: Call to `ReadData()` before main query starts.
* **1 Mark**: Prompting user for search input string.
* **1 Mark**: Clean linear search logic comparing searched input to getter values from `PackageList`.
* **1 Mark**: Correct tracking of "found" / "not found" state (Boolean flag or control flow).
* **1 Mark**: Correctly outputting detailed destination, type (Standard/Express), and formatting calculated cost values properly.
* **1 Mark**: Correct output for non-existent target ID input.
題目 2 · practical
23
An array stores information about commercial products. Each product is represented by an object of the class `Product`.

(a) Write object-oriented program code to declare the class `Product` with:
- private attribute `ProductID` (string)
- private attribute `Price` (real)
- a constructor that takes two parameters to initialize both attributes
- getter methods `GetProductID()` and `GetPrice()`

[5 marks]

(b) Declare a global 1D array `ProductList` of size 10 to store `Product` objects.
Write code to populate `ProductList` with the following 10 items in the given order:
1. ID: "P101", Price: 99.99
2. ID: "P102", Price: 12.50
3. ID: "P103", Price: 45.10
4. ID: "P104", Price: 5.00
5. ID: "P105", Price: 85.00
6. ID: "P106", Price: 65.20
7. ID: "P107", Price: 15.00
8. ID: "P108", Price: 30.00
9. ID: "P109", Price: 72.50
10. ID: "P110", Price: 50.00

[3 marks]

(c) Write a recursive procedure `RecursiveSort` that implements an insertion sort algorithm.
- The procedure must take two parameters: the array to sort, and an integer `n` representing the number of elements to process.
- It must sort the array in ascending order of the `Price` attribute.

[8 marks]

(d) Write a recursive function `RecursiveSearch` to perform a binary search for a specific price.
- The function must take four parameters: the array, the lower bound index, the upper bound index, and the target price (real).
- It must return the integer index of the matching product in the array, or -1 if the product is not found.

[5 marks]

(e) Write the main program code to perform the following actions:
1. Call `RecursiveSort` to sort the elements in `ProductList`.
2. Print the ID and price of each sorted product in the console.
3. Call `RecursiveSearch` to search for the product with price `45.10` and print its index position or a "Not found" message.

[2 marks]
查看答案詳解

解題

An elegant solution in Python 3:

```python
class Product:
def __init__(self, product_id, price):
self.__ProductID = product_id
self.__Price = price

def GetProductID(self):
return self.__ProductID

def GetPrice(self):
return self.__Price

# Initialize array
ProductList = [
Product("P101", 99.99),
Product("P102", 12.50),
Product("P103", 45.10),
Product("P104", 5.00),
Product("P105", 85.00),
Product("P106", 65.20),
Product("P107", 15.00),
Product("P108", 30.00),
Product("P109", 72.50),
Product("P110", 50.00)
]

def RecursiveSort(arr, n):
# Base case
if n <= 1:
return

# Sort first n-1 elements
RecursiveSort(arr, n - 1)

# Insert last element into its correct sorted position
last = arr[n - 1]
j = n - 2

while j >= 0 and arr[j].GetPrice() > last.GetPrice():
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = last

def RecursiveSearch(arr, low, high, target):
if high < low:
return -1

mid = (low + high) // 2

# Using float threshold for comparison
if abs(arr[mid].GetPrice() - target) < 0.0001:
return mid
elif arr[mid].GetPrice() > target:
return RecursiveSearch(arr, low, mid - 1, target)
else:
return RecursiveSearch(arr, mid + 1, high, target)

# Main Execution
RecursiveSort(ProductList, len(ProductList))

print("Sorted Product List:")
for p in ProductList:
print(f"ID: {p.GetProductID()}, Price: {p.GetPrice():.2f}")

target_price = 45.10
index = RecursiveSearch(ProductList, 0, len(ProductList) - 1, target_price)
if index != -1:
print(f"
Product with price {target_price:.2f} found at index: {index} (ID: {ProductList[index].GetProductID()})")
else:
print(f"
Product with price {target_price:.2f} not found.")
```

評分準則

Part (a) [Total: 5 marks]
- 1 mark: Defining `Product` class with appropriate constructor signature.
- 1 mark: Private instance attributes defined/initialized correctly (double leading underscores in Python or `private` keyword in Java/VB).
- 1 mark: Both constructor attributes mapped correctly to object variables.
- 1 mark: Correct implementation of getter `GetProductID()` returning private attribute value.
- 1 mark: Correct implementation of getter `GetPrice()` returning private attribute value.

Part (b) [Total: 3 marks]
- 1 mark: Declaring array `ProductList` structure of size 10 containing `Product` items.
- 2 marks: Populating all 10 records with exact data matches as requested (1 mark for partial/incomplete population).

Part (c) [Total: 8 marks]
- 1 mark: Header signature for `RecursiveSort` with parameters for array and integer limit `n`.
- 1 mark: Base case test of recursion (e.g. `n <= 1`) to halt and trigger backtracking.
- 1 mark: Correct recursive call made using a size of `n - 1`.
- 1 mark: Temporary backup of item at `n - 1` position.
- 2 marks: Correct condition loop (while loop indexes correctly checking array limits and matching value comparisons using `GetPrice()`).
- 1 mark: Shifting elements up inside the shifting loop.
- 1 mark: Reinserting backed-up element into its sorted index location.

Part (d) [Total: 5 marks]
- 1 mark: Correct signature including boundary parameters (`low`, `high`) and target search parameter.
- 1 mark: Boundary termination test (e.g. `high < low` or similar condition returning -1).
- 1 mark: Calculating exact middle offset index (`mid = (low + high) // 2`).
- 1 mark: Direct/approximate equivalence search matching mid element returning index.
- 1 mark: Recursive binary splitting paths calling function with modified boundaries.

Part (e) [Total: 2 marks]
- 1 mark: Call sorting function and output formatted array listing sequentially.
- 1 mark: Execution output verification displaying sorted items correctly and locating matching price index `45.10`.
題目 3 · Binary Tree Node File Operations
24
A binary tree is used to store sorted data. Each node in the tree consists of a data value (string), a left pointer (integer), and a right pointer (integer). You are required to implement this binary tree using object-oriented programming in a practical coding environment. Create a text file named 'TreeData.txt' to store node data. Each line of the text file contains the details of a single node in the format: index,data,leftpointer,rightpointer. For example:
0,Mango,1,2
1,Apple,-1,-1
2,Orange,-1,-1

Write a program to implement the binary tree by completing the following tasks:

1. Define a class 'Node' with the following private attributes:
- 'Data' (String)
- 'LeftPointer' (Integer)
- 'RightPointer' (Integer)
Define a constructor to initialize these attributes to values passed as parameters. Implement getter and setter methods for all three attributes.

2. In the main program, declare a 1-dimensional array named 'Tree' of size 20 of type 'Node'. Initialize all elements of the array to null/None.

3. Write a procedure 'LoadTree()' that opens the file 'TreeData.txt', reads it line-by-line, parses the index, data, left pointer, and right pointer values, instantiates a 'Node' object with these values, and stores the object in the 'Tree' array at the specified index. Implement exception handling to manage cases where the file cannot be opened.

4. Write a recursive procedure/function 'InOrder(Index)' that performs an in-order traversal of the tree starting at the given Index, outputting the data value of each node as it is visited.

5. Write main program code to call 'LoadTree()' and then call 'InOrder(0)' to output the contents of the tree. Test your program with sample data and take a screenshot of the output.
查看答案詳解

解題

class Node:
def __init__(self, data, left_pointer, right_pointer):
self.__data = data
self.__left_pointer = left_pointer
self.__right_pointer = right_pointer

def get_data(self):
return self.__data

def get_left_pointer(self):
return self.__left_pointer

def get_right_pointer(self):
return self.__right_pointer

def set_data(self, data):
self.__data = data

def set_left_pointer(self, left_pointer):
self.__left_pointer = left_pointer

def set_right_pointer(self, right_pointer):
self.__right_pointer = right_pointer

Tree = [None] * 20

def LoadTree():
try:
file = open("TreeData.txt", "r")
for line in file:
line = line.strip()
if line != "":
parts = line.split(",")
index = int(parts[0])
data = parts[1]
left = int(parts[2])
right = int(parts[3])
Tree[index] = Node(data, left, right)
file.close()
except IOError:
print("Error: TreeData.txt file could not be opened.")

def InOrder(index):
if index != -1 and Tree[index] is not None:
InOrder(Tree[index].get_left_pointer())
print(Tree[index].get_data())
InOrder(Tree[index].get_right_pointer())

# Main Program Execution
if __name__ == "__main__":
# Example TreeData.txt content:
# 0,Mango,1,2
# 1,Apple,-1,-1
# 2,Orange,-1,-1
LoadTree()
print("In-order Traversal:")
InOrder(0)

評分準則

1. Class 'Node' Definition [5 Marks]
- 1 Mark: Class 'Node' defined with three private attributes ('Data', 'LeftPointer', 'RightPointer') and correct data types.
- 1 Mark: Constructor defined with parameters initializing all attributes.
- 3 Marks: Getters and setters written correctly for all three attributes.

2. Array Declaration and Setup [2 Marks]
- 1 Mark: 1D array 'Tree' declared with 20 elements.
- 1 Mark: Initialized to empty/null values.

3. 'LoadTree' Procedure [8 Marks]
- 1 Mark: Correctly opening and closing 'TreeData.txt' with error handling (try/except or try/catch block).
- 2 Marks: Iterating through each line of the file and stripping whitespace.
- 2 Marks: Splitting each line by comma and correctly parsing index, left, and right pointers to integers.
- 2 Marks: Instantiating a new 'Node' object using the parsed data.
- 1 Mark: Storing the instantiated object at the correct array index corresponding to the line's index.

4. 'InOrder' Traversal Procedure [6 Marks]
- 1 Mark: Base case check ensuring the index is not -1 and array slot is not null/None.
- 2 Marks: Correct recursive call for the left pointer child: 'InOrder(Tree[index].get_left_pointer())'.
- 1 Mark: Correct statement to print/output the data of the current node.
- 2 Marks: Correct recursive call for the right pointer child: 'InOrder(Tree[index].get_right_pointer())'.

5. Main Program Execution and Testing [3 Marks]
- 1 Mark: Main program calls 'LoadTree()' first.
- 1 Mark: Main program calls 'InOrder(0)' to start traversing from root index 0.
- 1 Mark: Clean execution and output matching the expected sorted sequence of strings.

想知道自己有幾分把握?

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

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

免費開始練習