An original Thinka practice paper modelled on the structure and difficulty of the Jun 2026 (V1) Cambridge International A Level Computer Science (9618) paper. Not affiliated with or reproduced from Cambridge.
Paper 11 (Theory Fundamentals)
Answer all questions. Calculators must not be used. Write in dark blue or black pen in the spaces provided.
7 题目 · 75 分
题目 1 · short_answer
11 分
(a) Convert the denary integer 107 into an 8-bit unsigned binary number. [1]
(b) (i) Convert the denary integer -75 into an 8-bit two's complement integer. Show your working. [2]
(ii) The following 8-bit pattern represents a signed integer in two's complement form:
11100101
Convert this binary pattern into denary. Show your working. [2]
(c) Add the following two 8-bit two's complement integers:
01001100 + 01011010 ----------
Show your calculation. [2]
State whether an overflow error has occurred and give a reason for your answer. [2]
(d) Explain why software developers frequently use hexadecimal notation rather than binary when viewing memory dumps. [2]
Overflow evaluation: - An overflow error has occurred. - Reason: Two positive numbers (with sign bits 0) were added together and resulted in a negative value (sign bit 1) // The result (+166) exceeds the upper bound of 8-bit two's complement (+127).
(d) Hexadecimal is much shorter and more compact than binary (one hex digit represents 4 binary bits / a nibble), making it quicker to read and interpret. It also reduces human errors when transcribing or reading long sequences of 1s and 0s.
评分标准
(a) 1 mark for correct 8-bit binary value: 01101011.
(b)(i) 1 mark for correct intermediate working (e.g. +75 = 01001011, one's complement = 10110100). 1 mark for final answer: 10110101.
(b)(ii) 1 mark for showing valid method (e.g. place values: -128 + 64 + 32 + 4 + 1 OR two's complement negation: 00011011 = 27). 1 mark for correct denary value: -27.
(c) Addition: 1 mark for working showing correct carry bits. 1 mark for correct sum: 10100110. Overflow: 1 mark for stating that overflow has occurred. 1 mark for valid reason: Two positive numbers added together gave a negative result / sum exceeds the maximum positive value (+127) that can be stored in 8 bits.
(d) 1 mark per valid point (max 2): - Hexadecimal is more compact / takes up less space on the screen. - Easier for humans to read / write / remember compared to long strings of binary digits. - Less prone to transcription errors. - Straightforward 1-to-1 conversion between 1 hex digit and 4 binary bits (1 nibble).
题目 2 · short_answer
11 分
(a) (i) Convert the denary value 389 into packed Binary Coded Decimal (BCD). [2]
(ii) State one practical application where Binary Coded Decimal (BCD) is used. [1]
(b) Describe two differences between the standard ASCII character set and the Unicode character set. [2]
(c) A digital recording of an orchestral piece is captured.
(i) State what is meant by the terms sampling rate and sampling resolution. [2]
(ii) The audio piece is 30 seconds long. It is recorded in stereo (2 channels) with a sampling rate of 44.1 kHz (44,100 Hz) and a sampling resolution of 16 bits.
Calculate the file size of the uncompressed audio recording in mebibytes (MiB). Show all your working. [3]
(d) State one advantage of using Run-Length Encoding (RLE) to compress graphic data. [1]
查看答案详解收起答案详解
解题
(a)(i) Convert each denary digit into a 4-bit nibble: 3 = 0011 8 = 1000 9 = 1001 Result: 0011 1000 1001 (or represented as a full 2 bytes: 0000 0011 1000 1001).
(a)(ii) Displaying digits on 7-segment digital clocks / electronic calculators / financial systems where decimal rounding errors must be avoided.
(b) 1. Bit length: ASCII standard uses 7 bits per character (extended uses 8 bits), whereas Unicode uses up to 32 bits (e.g. UTF-8, UTF-16, UTF-32). 2. Character capacity: ASCII can only represent up to 128 (or 256) characters mainly for English text, whereas Unicode can represent over 1,000,000 distinct characters covering all global languages, mathematical symbols, and emojis.
(c)(i) Sampling rate: The number of sound samples captured per unit of time (per second), measured in Hertz (Hz). Sampling resolution: The number of bits used to represent the amplitude/sound level of each sample.
(d) RLE is a lossless compression technique, ensuring that the original image is fully restored with zero loss of quality, and it significantly reduces file size for images with repeated adjacent pixel values.
评分标准
(a)(i) 1 mark for converting digits to binary nibbles (0011, 1000, 1001). 1 mark for correct packed BCD string: 0011 1000 1001 (allow leading zeroes: 0000 0011 1000 1001).
(a)(ii) 1 mark for valid practical use: Seven-segment digital displays / calculators / accounting and financial calculation hardware.
(b) 1 mark per valid difference (max 2): - ASCII uses 7 (or 8) bits per character whereas Unicode uses 16/32 bits (or variable 8–32 bits). - ASCII represents 128 (or 256) characters whereas Unicode represents over 1,000,000 characters. - ASCII only supports English/basic Latin characters whereas Unicode supports multiple languages / international character sets / emojis.
(c)(i) 1 mark for sampling rate: Number of audio samples recorded/taken per second. 1 mark for sampling resolution: Number of bits used to store/encode each sample.
(c)(ii) 1 mark for multiplying duration, sample rate, channels, and sample resolution: 30 * 44100 * 16 * 2 (or 30 * 44100 * 2 * 2 bytes). 1 mark for dividing total bytes (5,292,000) by 1024 * 1024 (or 1,048,576). 1 mark for correct final value: 5.05 MiB (accept answers in range 5.04 to 5.05 MiB, or 5,292,000 / 1,048,576 MiB).
(d) 1 mark for valid advantage: It is lossless / original data can be reconstructed exactly // Very efficient at compressing images with long repeated sequences of the same colour/pixels.
题目 3 · Architecture & Assembly Language
9 分
(a) An assembly language instruction contains an opcode and an operand.
Identify the addressing mode used in each of the following instructions:
(i) `LDM #48` [1]
(ii) `LDD 150` [1]
(iii) `LDX 150` [1]
(b) Explain the difference between direct addressing and indirect addressing. [2]
(c) The following table shows part of the main memory of a computer system:
(a) (i) Immediate addressing (ii) Direct addressing (iii) Indexed addressing
(b) Direct addressing: The address part of the instruction holds the memory location where the data/operand is stored. Indirect addressing: The address part of the instruction holds the memory location that contains the effective/target address where the data/operand is stored.
(a) 1 mark for each correct mode: - (i) Immediate [1] - (ii) Direct [1] - (iii) Indexed [1]
(b) 1 mark per point (max 2): - MP1: In direct addressing, the operand is the actual memory address where the data is stored. [1] - MP2: In indirect addressing, the operand specifies a memory address that contains the target/effective memory address of the data. [1]
(c) 4 marks total for trace table: - MP1: Correct initialisation of ACC (0, 300) and locations 350 (0) and 351 (300). [1] - MP2: Correct values for iteration 1: ACC (12, 300, 301), Location 350 (12), Location 351 (301). [1] - MP3: Correct values for iteration 2 and iteration 3: ACC (5, 17, 301, 302, then 8, 25, 302, 303), Location 350 (17, then 25), Location 351 (302, then 303). [1] - MP4: Loop terminates correctly when location 351 reaches 303 and final OUTPUT shows 25. [1]
题目 4 · Theory
18 分
A logistics company, FastFreight, manages a fleet of delivery vehicles and tracks their servicing history across various authorised workshops.
(a) (i) Explain three limitations of a traditional file-based approach that are overcome by using a relational database management system (RDBMS). [3]
(ii) Explain the role of a foreign key in maintaining referential integrity between tables. [3]
(b) Initially, the fleet data is recorded in a single unnormalised table structure:
Assume that: * `RegistrationNo` uniquely identifies a vehicle. * `MaintenanceID` uniquely identifies a specific maintenance event. * `WorkshopID` uniquely identifies an authorised workshop. * Each vehicle can have many maintenance events, but each maintenance event is performed on exactly one vehicle by exactly one workshop.
(i) State what is required for a database relation to be in: * First Normal Form (1NF) * Second Normal Form (2NF) * Third Normal Form (3NF) [3]
(ii) Normalise the data into Third Normal Form (3NF).
Write the relational schema for each table using the format: `TableName(PrimaryKey, NonKeyAttribute1, ...)`
Underline all primary keys and identify any foreign keys. [4]
(c) (i) Write an SQL Data Definition Language (DDL) command to create the `MAINTENANCE` table defined in part (b)(ii).
Ensure appropriate SQL data types are used (e.g. `VARCHAR(n)`, `DATE`, `REAL`, etc.) and that primary and foreign keys are explicitly declared. Assume `RegistrationNo` is `VARCHAR(10)` and `WorkshopID` is `VARCHAR(6)`. [2]
(ii) Write an SQL Data Manipulation Language (DML) script to display the `WorkshopName`, `MaintenanceDate`, and `Cost` for all maintenance records completed after `'2024-01-01'` where the `Cost` is greater than `500.00`.
The output must be sorted in descending order of `Cost`. [3]
查看答案详解收起答案详解
解题
(a) (i) Limitations of file-based approach overcome by an RDBMS: 1. Data Redundancy: In file-based systems, identical data is duplicated across multiple separate files, wasting storage; a relational database uses linked tables/normalisation so each fact is stored only once. 2. Data Inconsistency: Updating data in one file does not automatically update duplicate entries in other files; an RDBMS ensures global consistency via centralised storage and relationships. 3. Program-Data Dependence: In file-based systems, application programs are tied to physical file formats, requiring code changes whenever file formats change; an RDBMS provides data independence (separating the logical schema from physical storage). (Accept other valid points: Complex data retrieval / queries, lack of built-in concurrency control, weaker security/access controls).
(a) (ii) * A foreign key is an attribute (or collection of attributes) in one table that matches the primary key of another related table. * Referential integrity ensures that foreign key values must always match a valid, existing primary key value in the referenced parent table (or be null). * It prevents orphan records (e.g., prevents adding a maintenance record referencing a non-existent vehicle or deleting a vehicle record that still has associated maintenance history).
(b) (i) * 1NF: Contains no repeating groups / all attributes are atomic / each record has a primary key. * 2NF: It is in 1NF AND contains no partial key dependencies (all non-key attributes are fully functionally dependent on the entire primary key). * 3NF: It is in 2NF AND contains no transitive dependencies (no non-key attribute depends on another non-key attribute).
(b) (ii) Relational Schema in 3NF: * `VEHICLE(RegistrationNo, Model, CapacityKg)` * `WORKSHOP(WorkshopID, WorkshopName, WorkshopCity)` * `MAINTENANCE(MaintenanceID, MaintenanceDate, Cost, RegistrationNo, WorkshopID)`
Foreign Keys: * `RegistrationNo` in `MAINTENANCE` references `VEHICLE(RegistrationNo)` * `WorkshopID` in `MAINTENANCE` references `WORKSHOP(WorkshopID)`
(c) (ii) ```sql SELECT WORKSHOP.WorkshopName, MAINTENANCE.MaintenanceDate, MAINTENANCE.Cost FROM WORKSHOP INNER JOIN MAINTENANCE ON WORKSHOP.WorkshopID = MAINTENANCE.WorkshopID WHERE MAINTENANCE.MaintenanceDate > '2024-01-01' AND MAINTENANCE.Cost > 500.00 ORDER BY MAINTENANCE.Cost DESC; ```
评分标准
(a) (i) [Max 3 marks] 1 mark per valid limitation clearly explained (up to 3): * Data redundancy: Duplicate data stored across separate files // relational tables minimise duplication. * Data inconsistency / integrity issues: Updates to one file may not propagate // relational database maintains uniform state. * Program-data dependence: File structure changes require program code updates // DBMS provides abstraction/independence. * Complex data retrieval: Requires custom search programs in file systems // SQL allows complex queries in relational databases.
(a) (ii) [3 marks] * MP1: Definition of foreign key (attribute in one table referencing/matching the primary key of another table). [1] * MP2: Explanation of referential integrity (foreign key value must correspond to an existing primary key value in the parent table / cannot be invalid). [1] * MP3: Consequence/prevention (prevents orphan records // stops accidental deletion of parent records with active references). [1]
(b) (i) [3 marks] * 1NF: No repeating groups / attributes are atomic. [1] * 2NF: In 1NF and no partial dependencies / all non-key fields depend on the whole primary key. [1] * 3NF: In 2NF and no transitive dependencies / no non-key field depends on another non-key field. [1]
(b) (ii) [4 marks] * MP1: `VEHICLE` table with correct attributes and `RegistrationNo` identified as PK. [1] * MP2: `WORKSHOP` table with correct attributes and `WorkshopID` identified as PK. [1] * MP3: `MAINTENANCE` table with correct attributes and `MaintenanceID` identified as PK. [1] * MP4: `RegistrationNo` and `WorkshopID` correctly identified as Foreign Keys in `MAINTENANCE`. [1]
(c) (i) [2 marks] * MP1: Correct `CREATE TABLE MAINTENANCE (...)` syntax including appropriate data types for all 5 fields. [1] * MP2: Correct `PRIMARY KEY` and both `FOREIGN KEY ... REFERENCES ...` constraints correctly specified. [1]
(c) (ii) [3 marks] * MP1: `SELECT WorkshopName, MaintenanceDate, Cost` (with or without table prefixes). [1] * MP2: Correct `FROM ... INNER JOIN ... ON ...` linking `WORKSHOP` and `MAINTENANCE` (or equivalent `FROM WORKSHOP, MAINTENANCE WHERE WORKSHOP.WorkshopID = MAINTENANCE.WorkshopID`). [1] * MP3: Correct `WHERE` filter (`MaintenanceDate > '2024-01-01' AND Cost > 500.00`) AND `ORDER BY Cost DESC`. [1]
题目 5 · Hardware, Logic & Graphics
6.5 分
A graphic design company produces images for an interactive advertising display.
(a) Describe two differences between a bitmap image and a vector graphic. [2]
(b) An uncompressed bitmap image has a resolution of \(1024 \times 768\) pixels and a colour depth of 16 bits. Calculate the file size of the raw image data in mebibytes (MiB). Show all your working. [2.5]
(c) (i) The designer decides to reduce the colour depth of the image so that it uses a maximum palette of 256 colours. State the minimum colour depth (in bits per pixel) required for 256 colours. [1]
(ii) State one effect that reducing the colour depth has on the visual appearance of the image. [1]
查看答案详解收起答案详解
解题
(a) Differences: 1. Representation: A bitmap image is stored as an array/grid of pixels (each with a specific colour value), whereas a vector graphic is defined by objects/paths using mathematical equations and geometric properties (e.g. coordinates, stroke, fill). 2. Scaling: Bitmaps lose clarity / suffer pixelation when enlarged, while vector graphics are resolution-independent and scale infinitely without quality loss.
(c) (i) \(2^8 = 256\), so 8 bits per pixel. (ii) Reduction in colour accuracy / colour banding / loss of smooth gradients (posterisation).
评分标准
(a) 1 mark for each valid difference (max 2): - MP1: Bitmap is composed of pixels // vector is made of geometric shapes / objects / formulas / primitives. - MP2: Bitmap becomes pixelated / loses quality when enlarged // vector scales without loss of quality / is resolution-independent. - MP3: Bitmap file size depends on resolution/colour depth // vector file size depends on number of objects / complexity. [Total: 2 marks]
(b) Mark breakdown: - MP1: Correct formula for total bits/bytes: \((1024 \times 768 \times 16) / 8\) or \(1024 \times 768 \times 2\) [1 mark] - MP2: Division by \(1024 \times 1024\) (or \(2^{20}\)) to convert to MiB [0.5 mark] - MP3: Correct final answer: \(1.5\) (MiB) [1 mark] [Total: 2.5 marks]
(c) (i) 8 (bits / bits per pixel) [1 mark] (ii) Colour banding / posterisation / fewer colours available / less realistic colour gradations [1 mark] [Total: 2 marks]
题目 6 · Hardware, Logic & Graphics
6.5 分
A graphic designer is creating a brand identity for a company. The logo must be scalable so that it can be printed on a small business card or enlarged for a highway billboard.
(a) (i) Explain why vector graphics are more suitable than bitmap images for creating this scalable logo. [2]
(a) (ii) Vector graphic images are defined using drawing objects and geometric properties. State two drawing objects and, for each, identify one property stored in the vector file. [2]
(b) (i) The computer's primary storage uses both Static RAM (SRAM) and Dynamic RAM (DRAM). Describe one operational difference between SRAM and DRAM. [1.5]
(b) (ii) State what is meant by the term non-volatile in relation to storage devices. [1]
查看答案详解收起答案详解
解题
(a)(i) Vector graphics store images as mathematical equations and geometric primitives rather than individual pixels. When scaled up (e.g. for a billboard), the shapes are recalculated dynamically, preventing pixelation and maintaining sharpness, unlike bitmap images which lose resolution and show individual pixel blocks when enlarged.
(a)(ii) Examples of drawing objects and properties: - Object: Rectangle / Polygon -> Property: width, height, stroke colour, fill colour, corner radius, coordinates of vertices. - Object: Circle / Ellipse -> Property: centre \((x, y)\), radius, fill colour, border thickness. - Object: Line -> Property: start point \((x_1, y_1)\), end point \((x_2, y_2)\), line style/thickness, line colour.
(b)(i) Operational difference: - DRAM consists of a transistor and capacitor per bit; the capacitor leaks charge over time and therefore must be refreshed periodically to maintain stored data. - SRAM uses multiple transistors configured as flip-flops; it does not leak charge and does not require refreshing as long as power is maintained (also making it faster and more expensive).
(b)(ii) Non-volatile memory retains its contents/data even when electrical power is disconnected/switched off.
评分标准
(a)(i) [2 marks max] - 1 mark for: vector images are based on mathematical formulas / equations / vectors (not a fixed grid of pixels). - 1 mark for: vector images can be scaled/resized without pixelation / loss of resolution / quality loss.
(a)(ii) [2 marks total] - 1 mark for first object and a valid associated property. - 1 mark for second object and a valid associated property. (Accept: line, rectangle, circle, curve, polygon with valid properties such as stroke width, fill colour, coordinates, radius).
(b)(i) [1.5 marks total] - 1 mark for stating that DRAM requires periodic refreshing while SRAM does not. - 0.5 mark for explaining the physical mechanism (DRAM uses capacitors that leak charge vs SRAM uses flip-flops / bistable latches) OR stating SRAM is faster / uses more transistors.
(b)(ii) [1 mark total] - 1 mark for: data is not lost / contents are retained when power is removed / switched off.
题目 7 · theory
13 分
Veloce Logistics manages several regional distribution depots that communicate with a central headquarters.
(a) (i) State two differences between a Local Area Network (LAN) and a Wide Area Network (WAN). [2]
(ii) The company uses a client-server model across its network instead of a peer-to-peer (P2P) model. Explain two advantages to Veloce Logistics of using a client-server model. [4]
(b) The local wired network within each depot uses Ethernet with Carrier Sense Multiple Access with Collision Detection (CSMA/CD). Describe the process followed by CSMA/CD when a workstation transmits data and a collision occurs. [4]
(c) (i) A computer in the main office has the IPv4 address `192.168.10.45` and a subnet mask of `255.255.255.0`. Identify the Network ID and the Host ID for this computer.
(ii) Explain one reason why Veloce Logistics plans to upgrade its addressing scheme from IPv4 to IPv6. [1]
查看答案详解收起答案详解
解题
(a) (i) - LAN covers a small geographical area (e.g., single building/site), whereas WAN covers a large geographical area (e.g., across multiple cities/countries). - LAN infrastructure is privately owned and maintained by the organisation, whereas WAN relies on public or third-party telecommunication carriers (e.g. telecom providers, satellites, leased lines).
(a) (ii) Advantage 1: - Centralised security and access control [1] — permissions and user accounts can be managed in one location to prevent unauthorised access to logistics databases [1]. Advantage 2: - Centralised data backup / data integrity [1] — critical shipment tracking records are stored on dedicated central servers, so regular backups can be performed without relying on individual depot workstations [1]. (Accept other valid points: centralised resource sharing / centralised software installation and updates).
(b) 1. Station listens to the carrier / transmission medium (carrier sensing) to determine if it is idle / free. 2. If idle, the station begins transmitting the frame and continues to listen to the channel. 3. If a collision is detected (voltage pulse or signal mismatch), the transmitting station immediately aborts transmission. 4. A jam signal is transmitted onto the network to notify all other devices of the collision. 5. The station waits for a random period of time (backoff period) before re-checking the carrier and attempting retransmission.
(c) (ii) - IPv6 provides a substantially larger address space (≈ \(3.4 \times 10^{38}\) unique addresses compared to IPv4's \(2^{32}\) addresses), resolving the global shortage / exhaustion of available public IPv4 addresses (or allows direct addressing of many IoT sensors without NAT).
评分标准
(a)(i) [Max 2 marks] 1 mark for each valid difference (comparison required): - LAN covers a small/local geographic area / single site / building whereas WAN covers a large/broad geographic area / multi-site / country-wide [1] - LAN is owned/managed privately by the organisation whereas WAN uses third-party / telecommunication infrastructure / public carriers [1] - LAN typically offers higher data transfer speeds / lower latency compared to WAN [1]
(a)(ii) [Max 4 marks] 2 marks per advantage (1 mark for identifying advantage + 1 mark for expansion in context): - Centralised backup / recovery [1] -> backups can be scheduled from a single location without relying on individual workstations [1] - Centralised security / user management [1] -> access rights, authentication and policies can be enforced from a domain controller [1] - Centralised data storage / consistency [1] -> ensures all depots access the same up-to-date central tracking/inventory data [1] - Centralised software management [1] -> software updates and patches are distributed uniformly from servers [1]
(b) [Max 4 marks] 1 mark per bullet point (max 4): - Station checks / senses transmission medium to see if it is idle [1] - Transmission begins when medium is idle and station continues to listen during transmission [1] - Collision is detected if simultaneous transmissions occur [1] - A jam signal is sent to alert all connected devices [1] - Station stops transmitting and waits a random time (backoff period) before re-sensing and retransmitting [1]
(c)(ii) [1 mark] - IPv4 address space is exhausted / depleted // IPv6 provides a vastly larger pool of addresses (128-bit vs 32-bit) to connect many more devices without NAT [1]
Paper 21 (Fundamental Problem-solving & Programming Skills)
Answer all questions. Refer to the insert for pseudocode functions and operators. Write answers in the spaces provided.
9 题目 · 75 分
题目 1 · Basic Constructs & IDE Tools
4 分
A programmer is writing a modular program using an Integrated Development Environment (IDE).
(a) The programmer makes use of various IDE features during the coding and debugging stages.
(i) Describe how the IDE's dynamic syntax checking (or auto-completion / context-sensitive prompts) feature assists the programmer while writing code.
[2]
(ii) The programmer inserts a breakpoint into the program code during debugging.
Explain the purpose of a breakpoint in debugging program code.
[2]
查看答案详解收起答案详解
解题
(a)(i) - It checks code syntax in real-time as the programmer types. - It highlights errors immediately (e.g., using squiggly lines or colour changes) / suggests corrections or auto-completes keywords and variable names, reducing typing/syntax errors before compilation.
(a)(ii) - A breakpoint halts / pauses the execution of the program at a specific statement / line of code. - This allows the programmer to inspect the current contents of variables (in the watch window / symbol table) and execute subsequent lines one by one (single-stepping) to find logic errors.
评分标准
(a)(i) 1 mark per bullet point (Max 2): - Identifies syntax errors in real-time / as code is being typed [1] - Flags / highlights errors visually / provides immediate suggestions / auto-completion [1]
(a)(ii) 1 mark per bullet point (Max 2): - Pauses / halts program execution at a predetermined line / point [1] - Allows the programmer to inspect variable values / environment state / step through code line-by-line (single-stepping) [1]
题目 2 · Basic Constructs & IDE Tools
5 分
A program validates product identification codes entered by a user. Each product code is a string that must satisfy the following rules: - It must be exactly 8 characters long. - The first 3 characters must be uppercase alphabetic characters. - The 4th character must be a hyphen (`"-"`).
IF LENGTH(ProductCode) <> 8 THEN IsValid <- FALSE ELSE IF MID(ProductCode, 4, 1) <> "-" THEN IsValid <- FALSE ENDIF Prefix <- MID(ProductCode, 1, 3) IF Prefix <> UCASE(Prefix) THEN IsValid <- FALSE ENDIF ENDIF
IF IsValid = TRUE THEN OUTPUT "VALID" ELSE OUTPUT "INVALID" ENDIF ```
评分标准
1 mark for each of the following: - `INPUT ProductCode` (with appropriate declaration) [1] - Checking that `LENGTH(ProductCode) = 8` (or `<> 8`) [1] - Extracting 4th character using `MID(ProductCode, 4, 1)` and comparing to `"-"` [1] - Extracting first 3 characters and checking if equal to their `UCASE()` equivalent [1] - Correct selection construct logic resulting in outputting `"VALID"` and `"INVALID"` appropriately [1]
题目 3 · Software Engineering & Structured English
6.5 分
A logistics depot uses an automated weighing and classification station to process parcels.
The algorithm for processing a single parcel is described in Structured English as follows:
1. Input the parcel tracking reference number and the parcel weight in kilograms. 2. Check whether the weight is strictly greater than 0 and less than or equal to 30.0 kg. - If the weight is valid: - If the weight is less than or equal to 2.0 kg, set category to "Standard". - If the weight is greater than 2.0 kg and less than or equal to 10.0 kg, set category to "Heavy". - Otherwise, set category to "Bulky". - Output the tracking reference and the assigned category. - Otherwise: - Output an error message "Invalid parcel weight".
(a) Write pseudocode to implement this algorithm for one parcel. [4]
(b) The system needs to be tested using black-box testing.
(i) State two boundary (extreme) values that should be used to test the valid parcel weight range (0 to 30.0 kg inclusive). [1]
(ii) After deployment, the maximum allowed weight is increased from 30.0 kg to 35.0 kg due to a change in courier regulations.
Identify the type of maintenance required and justify your choice. [1.5]
查看答案详解收起答案详解
解题
(a) Example Pseudocode: ``` DECLARE TrackingRef : STRING DECLARE Weight : REAL DECLARE Category : STRING
INPUT TrackingRef INPUT Weight
IF Weight > 0.0 AND Weight <= 30.0 THEN IF Weight <= 2.0 THEN Category <- "Standard" ELSE IF Weight <= 10.0 THEN Category <- "Heavy" ELSE Category <- "Bulky" ENDIF ENDIF OUTPUT TrackingRef, ": ", Category ELSE OUTPUT "Invalid parcel weight" ENDIF ```
(b)(i) Boundary/extreme test values: - 0.0 (or just above 0.0, e.g., 0.1) and 30.0 (or 30.1 as invalid boundary).
(b)(ii) - Type of maintenance: Adaptive maintenance. - Justification: The code needs updating to adapt to external changes in courier regulations/business environment rather than fixing an existing error (corrective) or enhancing performance (perfective).
评分标准
(a) [Total: 4 marks] - 1 mark: Input of `TrackingRef` and `Weight` with appropriate variable declarations/types. - 1 mark: Outer `IF` condition checking `Weight > 0 AND Weight <= 30.0` (or equivalent nested structure) with correct `ELSE` branch outputting error. - 1 mark: Correct nested conditional logic for categorising `"Standard"`, `"Heavy"`, and `"Bulky"`. - 1 mark: Correct assignment to `Category` and output of tracking reference and category.
(b)(i) [Total: 1 mark] - 1 mark for any two valid boundary values: e.g., 0.1 / 0.01 / 30.0 (Accept: 0.0 as lower extreme boundary, 30.0 as upper boundary).
(b)(ii) [Total: 1.5 marks] - 0.5 mark: Adaptive (maintenance). - 1 mark: Justification stating that the system is altered to comply with new external requirements / changing regulations / new business operational rules.
题目 4 · Software Engineering & Structured English
6.5 分
A warehouse management system includes a module to validate scanned item barcode strings.
(a) The development team chooses an iterative life cycle model over the linear waterfall model for this software project.
State one benefit and one drawback of using an iterative model. [2]
(b) The module `ValidateBarcode` is specified in Structured English as follows:
- The function receives a single string parameter `Barcode`. - If the length of `Barcode` is not equal to 8, return `FALSE`. - Check each character from index 1 to 7: if any character is not an uppercase letter ('A' to 'Z'), return `FALSE`. - Check the 8th character: if it is not a numeric digit ('0' to '9'), return `FALSE`. - If all checks pass, return `TRUE`.
Write pseudocode for the function `ValidateBarcode`. [4.5]
查看答案详解收起答案详解
解题
(a) Benefit (any one): - Functional prototypes/versions are produced early in the development cycle. - Easier to accommodate changing user requirements or feedback between iterations. - Risks can be identified and mitigated earlier in the project.
Drawback (any one): - Regular client involvement/feedback is required throughout development. - Final project completion date and overall cost can be difficult to predict (scope creep).
(b) Example Pseudocode: ``` FUNCTION ValidateBarcode(Barcode : STRING) RETURNS BOOLEAN DECLARE Index : INTEGER DECLARE NextChar : CHAR
IF LENGTH(Barcode) <> 8 THEN RETURN FALSE ENDIF
FOR Index <- 1 TO 7 NextChar <- MID(Barcode, Index, 1) IF NextChar < 'A' OR NextChar > 'Z' THEN RETURN FALSE ENDIF NEXT Index
NextChar <- MID(Barcode, 8, 1) IF NextChar < '0' OR NextChar > '9' THEN RETURN FALSE ENDIF
RETURN TRUE ENDFUNCTION ```
评分标准
(a) [Total: 2 marks] - 1 mark: Valid benefit of iterative model (e.g. accommodates requirement changes / early delivery of functional sub-components / early risk identification). - 1 mark: Valid drawback of iterative model (e.g. uncertain final cost or schedule / requires frequent client engagement / risk of scope creep).
(b) [Total: 4.5 marks] - 0.5 mark: Correct `FUNCTION` header with parameter `Barcode : STRING` and `RETURNS BOOLEAN`, matching `ENDFUNCTION`. - 1 mark: Check for length equal to 8 (e.g., `LENGTH(Barcode) <> 8`) returning `FALSE`. - 1 mark: Loop iterating through indices 1 to 7 using string extraction (e.g., `MID(Barcode, Index, 1)`). - 1 mark: Validation of uppercase character range (`< 'A' OR > 'Z'`) with immediate return of `FALSE` (or flag equivalent). - 1 mark: Validation of 8th character for digit range (`'0'` to `'9'`) returning `FALSE`, and returning `TRUE` if all checks pass.
题目 5 · structured
8.5 分
A text file, `SensorLog.txt`, stores telemetry data generated by remote monitoring devices. Each line of the file represents one data record stored in the following format:
`###`
For example: `"SN402#2025-03-14 09:30#24.8#OK"`
Fields are separated by the hash character (`'#'`). Field numbering starts at 1, so in the example above: - Field 1 is `"SN402"` - Field 2 is `"2025-03-14 09:30"` - Field 3 is `"24.8"` - Field 4 is `"OK"`
You may assume the following built-in string functions are available: - `LENGTH(ThisString : STRING) RETURNS INTEGER` - `MID(ThisString : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING`
(a) Write pseudocode for a function `ExtractField(RecordString : STRING, FieldNumber : INTEGER) RETURNS STRING`.
The function searches `RecordString` and returns the substring corresponding to `FieldNumber`. If `FieldNumber` does not exist in `RecordString`, the function returns an empty string (`""`). [4.5]
(b) Write pseudocode for a procedure `FilterSensorData(InputFileName : STRING, TargetID : STRING, OutputFileName : STRING)`.
The procedure must: - Open `InputFileName` for reading and `OutputFileName` for writing. - Read each record from `InputFileName` until the end of the file is reached. - Use the `ExtractField()` function to check whether the `SensorID` matches `TargetID` and the `StatusCode` is equal to `"OK"`. - If both conditions are met, write the extracted `Reading` value (Field 3) as a new line to `OutputFileName`. - Close both files at the end. [4.0]
FOR Index <- 1 TO LENGTH(RecordString) CurrentChar <- MID(RecordString, Index, 1) IF CurrentChar = "#" THEN IF CurrentFieldNum = FieldNumber THEN RETURN ExtractedText ENDIF CurrentFieldNum <- CurrentFieldNum + 1 ExtractedText <- "" ELSE ExtractedText <- ExtractedText & CurrentChar ENDIF NEXT Index
IF CurrentFieldNum = FieldNumber THEN RETURN ExtractedText ELSE RETURN "" ENDIF ENDFUNCTION ```
(a) [4.5 Marks Total] - MP1: Correct function header and declarations including parameter types and return type `STRING` (0.5) - MP2: Initialising field counter and accumulator string, and loop through characters of `RecordString` (1.0) - MP3: Correct condition checking for delimiter `'#'` and updating `CurrentFieldNum` / resetting accumulator (1.0) - MP4: Appending non-delimiter characters to current field string (1.0) - MP5: Correctly returning field content for intermediate or terminal field, and returning `""` if field is absent (1.0)
(b) [4.0 Marks Total] - MP1: Correct procedure header and opening both files in appropriate modes (`READ` and `WRITE`) (1.0) - MP2: Correct loop reading lines until `EOF(InputFileName)` (1.0) - MP3: Calling `ExtractField` to obtain Field 1 and Field 4, and checking if `SensorID = TargetID` and `StatusCode = "OK"` (1.0) - MP4: Writing Field 3 (`ReadingValue`) to output file and closing both files after loop (1.0)
题目 6 · structured
8.5 分
A database maintenance program processes customer records stored in a text file named `CustomerAccounts.txt`. Each line in the file contains three fields separated by an asterisk (`'*'`):
`**`
For example: `"CUST8812*alex.taylor@domain.org*PREMIUM"`
You may assume the following built-in string functions are available: - `LENGTH(ThisString : STRING) RETURNS INTEGER` - `MID(ThisString : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING` - `LEFT(ThisString : STRING, Length : INTEGER) RETURNS STRING` - `RIGHT(ThisString : STRING, Length : INTEGER) RETURNS STRING`
(a) Write pseudocode for a function `ValidateEmail(EmailAddress : STRING) RETURNS BOOLEAN`.
The function validates an email address according to the following rules: 1. It must contain exactly one `'@'` character. 2. The `'@'` character must not be the first or last character. 3. There must be at least one `'.'` character located after the `'@'` character, but not as the final character of `EmailAddress`.
The function returns `TRUE` if all criteria are met, and `FALSE` otherwise. [4.5]
(b) Write pseudocode for a procedure `AuditSubscribers(SourceFileName : STRING, ErrorFileName : STRING)`.
The procedure must: - Open `SourceFileName` for reading and `ErrorFileName` for writing. - Process all records in `SourceFileName`. - Separate each line into `CustomerID`, `EmailAddress`, and `SubscriptionLevel`. - Validate `EmailAddress` using `ValidateEmail()`. - If `EmailAddress` is valid and `SubscriptionLevel` is equal to `"PREMIUM"`, increment a count of valid premium subscribers. - If `EmailAddress` is invalid, write the complete original line to `ErrorFileName`. - Close both files and output the total count of valid premium subscribers with an appropriate message. [4.0]
(a) [4.5 Marks Total] - MP1: Correct function header and initialisation of tracking variables (0.5) - MP2: Iterating through `EmailAddress` to count `'@'` and record its position (1.0) - MP3: Checking that `'@'` count is exactly 1 and position is neither 1 nor `LENGTH(EmailAddress)` (1.0) - MP4: Checking for `'.'` character at position > `AtPos` and < `LENGTH(EmailAddress)` (1.0) - MP5: Correctly returning `TRUE` when all conditions hold and `FALSE` otherwise (1.0)
(b) [4.0 Marks Total] - MP1: Correct procedure header, initialising counter, and opening files in `READ` and `WRITE` modes (1.0) - MP2: Loop until `EOF(SourceFileName)` and parsing delimiter `'*'` to extract fields (1.0) - MP3: Calling `ValidateEmail(Email)` and handling branching: incrementing `PremiumCount` if valid and `SubLevel = "PREMIUM"`; writing `CurrentLine` to `ErrorFileName` if invalid (1.0) - MP4: Closing both files and outputting `PremiumCount` with descriptive message (1.0)
题目 7 · theory
12 分
A helpdesk ticketing system uses a linear queue to store customer identifiers awaiting technical support.
The queue is implemented using a 1D array, `SupportQueue`, with bounds `1:6`. Two global integer pointer variables are used: * `HeadPointer` points to the first customer identifier in the queue. * `TailPointer` points to the last customer identifier added to the queue.
When the queue is empty, `HeadPointer` and `TailPointer` both contain the value `0`.
(a) (i) State the data access principle used by a queue. [1]
(ii) Explain one advantage of implementing a circular queue rather than a linear queue in a fixed-size array. [2]
(b) The array `SupportQueue` currently contains three customer identifiers:
(c) Write pseudocode for a procedure `EnqueueCustomer` that takes a customer identifier as a parameter and adds it to `SupportQueue`.
The procedure must: * take a parameter `CustomerID` of type `STRING` * output `"Queue is full"` if the queue cannot accept any more items * set `HeadPointer` to 1 if the queue was previously empty * update `TailPointer` and store `CustomerID` at the next available position in `SupportQueue`.
Assume `SupportQueue`, `HeadPointer`, and `TailPointer` are declared as global variables. [5]
查看答案详解收起答案详解
解题
(a) (i) FIFO / First In, First Out.
(ii) In a linear queue, when elements are dequeued, the space before `HeadPointer` is wasted and cannot be reused without shifting elements, leading to a situation where the queue appears full even if empty slots exist. In a circular queue, `TailPointer` wraps around to the beginning of the array (index 1) when the end is reached, allowing freed spaces to be reused.
(c) Pseudocode: ``` PROCEDURE EnqueueCustomer(CustomerID : STRING) IF TailPointer = 6 THEN OUTPUT "Queue is full" ELSE IF HeadPointer = 0 THEN HeadPointer <- 1 ENDIF TailPointer <- TailPointer + 1 SupportQueue[TailPointer] <- CustomerID ENDIF ENDPROCEDURE ```
评分标准
(a)(i) 1 mark for: - First In First Out // FIFO
(a)(ii) Max 2 marks: - In a linear queue, memory/locations at the front cannot be reused once elements are removed // space is wasted [1] - In a circular queue, pointers wrap around to index 1 when the upper bound is reached to reuse vacated spaces [1]
(b) 4 marks: - 1 mark for `HeadPointer = 3` - 1 mark for `TailPointer = 5` - 1 mark for correct elements (`"CUST82"`, `"CUST99"`, `"CUST14"`) at indices 3, 4, 5 respectively - 1 mark for indices 1, 2, 6 shown as empty/unoccupied or containing crossed-out/inactive data
(c) 5 marks: - 1 mark: Correct procedure header (with parameter `CustomerID : STRING` or `BYVAL CustomerID : STRING`) and `ENDPROCEDURE` - 1 mark: Checking if the queue is full (`TailPointer = 6` / `TailPointer >= 6`) and outputting error message - 1 mark: Checking if the queue is empty (`HeadPointer = 0`) and setting `HeadPointer <- 1` - 1 mark: Incrementing `TailPointer` by 1 (`TailPointer <- TailPointer + 1`) - 1 mark: Storing `CustomerID` into `SupportQueue[TailPointer]` within `ELSE` branch
题目 8 · free-response
6 分
The 1D array `InventoryCode` contains the following seven integer values:
The following pseudocode function searches the array for a specific integer value and terminates the search early once the target value has been found twice.
5. Iteration 4 (`CurrentIndex = 4`, `TotalFound = 1`): - `InventoryCode[4]` is `12` (= 12). Condition is TRUE. - `TotalFound <- 1 + 1 = 2` - `OUTPUT "Match at index 4"` - `IsFound <- TRUE` (or left as TRUE) - `CurrentIndex <- 4 + 1 = 5`.
6. Loop Condition Check: - `CurrentIndex <= 7 AND TotalFound < 2` evaluates to `5 <= 7 AND 2 < 2`, which is `TRUE AND FALSE = FALSE`. Loop terminates.
7. Post-Loop: - `IF NOT IsFound` is `NOT TRUE = FALSE` (no output). - `RETURN TotalFound` returns `2`.
评分标准
1 mark per marking point (max 6 marks): - MP1: Initialises `CurrentIndex` to 1, `TotalFound` to 0, and `IsFound` to `FALSE`. - MP2: Increments `CurrentIndex` through 2, 3, 4, 5 in correct sequence. - MP3: Updates `TotalFound` to 1 at index 2 and to 2 at index 4. - MP4: Updates `IsFound` to `TRUE` on the first match. - MP5: Correct outputs shown: `"Match at index 2"` and `"Match at index 4"` (allow without exact punctuation/quotes). - MP6: Loop terminates with `CurrentIndex` equal to 5 (no further iterations) and returns value `2`.
题目 9 · free-response
18 分
An agricultural research facility monitors environmental conditions across several greenhouses using automated sensor nodes.
There are 8 greenhouses, numbered 1 to 8. Each greenhouse contains 12 sensor nodes, numbered 1 to 12.
Data for each sensor node is stored in a record of type `SensorRecord` with the following fields: - `SensorID`: string identifier (e.g., "GH03-N07") - `Temperature`: real number representing temperature in degrees Celsius - `Humidity`: real number representing percentage relative humidity (0.0 to 100.0) - `Status`: single character representing sensor status ('A' = Active, 'F' = Faulty, 'I' = Inactive)
A 2D array `GridData` is used to store the `SensorRecord` data for all 8 greenhouses and 12 nodes per greenhouse.
(a) Write pseudocode to define the user-defined composite type `SensorRecord`. [4]
(b) Write pseudocode to declare the 2D array `GridData` to store the records for 8 greenhouses and 12 sensor nodes per greenhouse. [2]
(c) Write pseudocode for a procedure `InitialiseGrid` that sets default values for every record in the array `GridData`: - `SensorID` to an empty string `""` - `Temperature` to `-99.0` - `Humidity` to `-1.0` - `Status` to `'I'` [4]
(d) Write pseudocode for a function `AverageActiveTemp` that: - takes an integer parameter `GreenhouseNum` representing the greenhouse number (1 to 8) - calculates and returns the average (mean) temperature of all active sensors (`Status` = `'A'`) in that greenhouse as a `REAL` value - returns `-999.0` if there are no active sensors in the specified greenhouse. [5]
(e) Write pseudocode for a procedure `GenerateAlertReport` that: - scans the entire `GridData` array - checks every active sensor (`Status` = `'A'`) - outputs an alert message for any active sensor where `Temperature` is strictly greater than `38.0` OR `Humidity` is strictly less than `20.0` - outputs the message in the format: `"ALERT: Sensor " & SensorID & " at GH " & GreenhouseIndex & ", Node " & NodeIndex & " - Temp: " & Temperature & ", Humidity: " & Humidity` - outputs the total number of alerts generated at the end of the scan. [3]
查看答案详解收起答案详解
解题
Part (a): Define the composite record type using standard Cambridge pseudocode syntax: ```pseudocode TYPE SensorRecord DECLARE SensorID : STRING DECLARE Temperature : REAL DECLARE Humidity : REAL DECLARE Status : CHAR ENDTYPE ```
Part (b): Declare the global 2D array: ```pseudocode DECLARE GridData : ARRAY[1:8, 1:12] OF SensorRecord ```
Part (c): Iterate across both dimensions (greenhouse indices 1 to 8 and sensor node indices 1 to 12) to reset all fields: ```pseudocode PROCEDURE InitialiseGrid() DECLARE GHIndex : INTEGER DECLARE NodeIndex : INTEGER FOR GHIndex <- 1 TO 8 FOR NodeIndex <- 1 TO 12 GridData[GHIndex, NodeIndex].SensorID <- "" GridData[GHIndex, NodeIndex].Temperature <- -99.0 GridData[GHIndex, NodeIndex].Humidity <- -1.0 GridData[GHIndex, NodeIndex].Status <- 'I' NEXT NodeIndex NEXT GHIndex ENDPROCEDURE ```
Part (d): Sum the temperatures of all active sensors in the specified row/greenhouse and divide by the count, preventing division by zero if count is 0: ```pseudocode FUNCTION AverageActiveTemp(GreenhouseNum : INTEGER) RETURNS REAL DECLARE NodeIndex : INTEGER DECLARE TotalTemp : REAL DECLARE ActiveCount : INTEGER TotalTemp <- 0.0 ActiveCount <- 0 FOR NodeIndex <- 1 TO 12 IF GridData[GreenhouseNum, NodeIndex].Status = 'A' THEN TotalTemp <- TotalTemp + GridData[GreenhouseNum, NodeIndex].Temperature ActiveCount <- ActiveCount + 1 ENDIF NEXT NodeIndex IF ActiveCount > 0 THEN RETURN TotalTemp / ActiveCount ELSE RETURN -999.0 ENDIF ENDFUNCTION ```
Part (e): Traverse the entire 2D array, check compound conditions on active records, print the formatted output, and display total alert count: ```pseudocode PROCEDURE GenerateAlertReport() DECLARE GHIndex : INTEGER DECLARE NodeIndex : INTEGER DECLARE AlertCount : INTEGER AlertCount <- 0 FOR GHIndex <- 1 TO 8 FOR NodeIndex <- 1 TO 12 IF GridData[GHIndex, NodeIndex].Status = 'A' THEN IF GridData[GHIndex, NodeIndex].Temperature > 38.0 OR GridData[GHIndex, NodeIndex].Humidity < 20.0 THEN OUTPUT "ALERT: Sensor ", GridData[GHIndex, NodeIndex].SensorID, " at GH ", GHIndex, ", Node ", NodeIndex, " - Temp: ", GridData[GHIndex, NodeIndex].Temperature, ", Humidity: ", GridData[GHIndex, NodeIndex].Humidity AlertCount <- AlertCount + 1 ENDIF ENDIF NEXT NodeIndex NEXT GHIndex OUTPUT "Total alerts: ", AlertCount ENDPROCEDURE ```
评分标准
(a) 1 mark per point (max 4): - `TYPE SensorRecord` and `ENDTYPE` header and footer - `SensorID : STRING` - `Temperature : REAL` AND `Humidity : REAL` - `Status : CHAR`
(b) 1 mark per point (max 2): - `DECLARE GridData : ARRAY[1:8, 1:12]` (or `[1:8, 1:12]` bounds correctly shown) - `OF SensorRecord`
(c) 1 mark per point (max 4): - Correct procedure header `PROCEDURE InitialiseGrid()` and `ENDPROCEDURE` - Nested loop traversing dimensions 1 to 8 and 1 to 12 - Correct dot-notation access to record fields (e.g., `GridData[GHIndex, NodeIndex].Field`) - Setting all 4 fields to required initial values (`""`, `-99.0`, `-1.0`, `'I'`)
(d) 1 mark per point (max 5): - Function header taking `INTEGER` parameter and returning `REAL` (plus matching `ENDFUNCTION`) - Initialising accumulator and counter variables to 0 (or 0.0) - Loop traversing 1 to 12 for the fixed greenhouse index checking `Status = 'A'` - Accumulating temperature and incrementing counter for matching records - Checking counter > 0, returning `TotalTemp / ActiveCount` ELSE returning `-999.0`
(e) 1 mark per point (max 3): - Nested loop over both array dimensions checking `Status = 'A'` - Correct logical condition (`Temperature > 38.0 OR Humidity < 20.0`) and incrementing alert count - Correct alert message output format AND final alert count output
Paper 31 (Advanced Theory)
Answer all questions. Calculators are not permitted. Show all working clearly for dry-runs and numeric conversions.
11 题目 · 75 分
题目 1 · theory
5.5 分
A logistics tracking system manages parcels using custom data types.
(a) Explain the difference between a composite data type and a non-composite data type, giving one example of each. [2]
(b) Write pseudocode to define:
(i) An enumerated non-composite data type `TStatus` that can take one of the following values: `PENDING`, `IN_TRANSIT`, `DELIVERED`, `RETURNED`. [1]
(ii) A composite record data type `TPackage` that contains the following fields: - `TrackingID`: a string of characters - `Weight`: a real number - `CurrentStatus`: of type `TStatus` - `NextPackage`: a pointer referencing another record of type `TPackage` [2.5]
查看答案详解收起答案详解
解题
(a) - Non-composite data type: A fundamental or user-defined data type that does not reference or contain any other data types (e.g., enumerated type, pointer, INTEGER, BOOLEAN). - Composite data type: A user-defined data type constructed by combining multiple other existing data types into a single structure (e.g., record, class, set).
(b)(i) ``` TYPE TStatus = (PENDING, IN_TRANSIT, DELIVERED, RETURNED) ```
(b)(ii) ``` TYPE TPackagePtr = ^TPackage TYPE TPackage DECLARE TrackingID : STRING DECLARE Weight : REAL DECLARE CurrentStatus : TStatus DECLARE NextPackage : TPackagePtr ENDTYPE ``` (Note: Declaring `NextPackage : ^TPackage` directly is also accepted according to Cambridge standard pseudocode).
评分标准
(a) 1 mark for distinguishing non-composite vs composite definition; 1 mark for providing a valid example of each.
(b)(i) 1 mark for correct pseudocode declaration: `TYPE TStatus = (PENDING, IN_TRANSIT, DELIVERED, RETURNED)` (All 4 elements present, correct syntax).
(b)(ii) Max 2.5 marks: - 1 mark for correct record header and terminator (`TYPE TPackage` and `ENDTYPE`) - 1 mark for correctly declaring `TrackingID : STRING`, `Weight : REAL`, and `CurrentStatus : TStatus` - 0.5 marks for correct pointer declaration for `NextPackage` (either `^TPackage` or referencing a pointer type defined as `^TPackage`).
题目 2 · theory
5.5 分
A warehouse management system stores inventory records in a secondary storage file.
(a) Explain the difference between file organisation and file access method. [2]
(b) The system uses random file organisation to store records indexed by a numeric `ProductID`.
(i) Describe how a hashing algorithm is used to calculate the physical storage location of a record in this random file when a new record is inserted. [2]
(ii) Explain how a collision is handled using open addressing (linear probing) when inserting a record. [1.5]
查看答案详解收起答案详解
解题
(a) - File organisation: The physical arrangement and structure of data/records on secondary storage (e.g., serial, sequential, random). - File access: The method or strategy by which individual records are retrieved or stored (e.g., sequential access, direct/random access).
(b)(i) 1. The hashing function receives the key field value (`ProductID`) as input. 2. A mathematical computation (such as `ProductID MOD NumberOfSlots`) is applied to calculate a hash value. 3. This resulting hash value is converted into a physical block/record address or slot number where the record is directly stored.
(b)(ii) 1. If the target address generated by the hashing function is already occupied (a collision), 2. The system checks the next contiguous memory location / record address (slot + 1), 3. It continues searching linearly until the first empty/available bucket is found and writes the record there (wrapping around to the beginning if necessary).
评分标准
(a) 1 mark for defining file organisation (physical structure/arrangement of records on disk); 1 mark for defining file access (strategy/method used to locate and read/write records).
(b)(i) 2 marks: - 1 mark for stating that the key value (`ProductID`) is passed into a mathematical formula / hashing algorithm. - 1 mark for stating that the resulting hash value determines the direct block/record address where the record is written.
(b)(ii) 1.5 marks: - 1 mark for describing that the algorithm checks the next sequential / adjacent memory location / slot. - 0.5 marks for stating that the search continues iteratively until an empty / unoccupied slot is found.
题目 3 · Theory
6 分
A computer system stores real numbers using a 12-bit floating-point representation in two's complement form: - 8 bits for the mantissa - 4 bits for the exponent.
(a) Convert the following floating-point representation into denary. Show your working.
Mantissa: `10110000` Exponent: `0011` [2]
(b) The denary value `+9.75` is to be stored using the same 12-bit floating-point format.
Write the normalised floating-point representation for `+9.75`. Show your working.
Mantissa: Exponent: [3]
(c) State why the mantissa obtained in part (b) is normalised. [1]
查看答案详解收起答案详解
解题
(a) - Mantissa: `10110000` Since the sign bit is 1, this is a negative number. In two's complement: \(-1 + 0.25 + 0.125 = -0.625\) (or \(-\frac{5}{8}\)) - Exponent: `0011` \(= +3\) - Denary value: \(-0.625 \times 2^3 = -0.625 \times 8 = -5\)
(b) - Convert \(+9.75\) to fixed-point binary: \(9 = 1001_2\) \(0.75 = 0.11_2\) \(+9.75 = 1001.11_2\) - Normalise by shifting the binary point 4 places to the left: \(0.1001110_2 \times 2^4\) - Mantissa (8 bits): `01001110` - Exponent (\(+4\) in 4-bit two's complement): `0100`
(c) - A positive number in two's complement is normalised when the first two bits are `01` (the sign bit and the first bit after the binary point are different).
评分标准
(a) 1 mark for calculating the mantissa as \(-0.625\) (or \(-\frac{5}{8}\)) AND exponent as \(+3\) 1 mark for correct final denary value: \(-5\) (or \(-5.0\))
(b) 1 mark for converting \(+9.75\) to binary: \(1001.11\) (or \(1001.1100\)) 1 mark for correct 8-bit mantissa: `01001110` 1 mark for correct 4-bit exponent: `0100`
(c) 1 mark for any one of: - The first two bits are different / start with `01`. - The sign bit is `0` and the most significant digit after the binary point is `1`.
题目 4 · short_answer
4 分
A software distribution company uses the BitTorrent protocol to distribute large disk image files to users.
(a) Explain the role of a tracker in the BitTorrent protocol. [2]
(b) Describe how a BitTorrent client downloads a file from multiple peers and reconstructs the complete file. [2]
查看答案详解收起答案详解
解题
(a) A tracker is a coordinating server in a peer-to-peer BitTorrent network. It does not store or transmit any payload/file data itself. Instead, it maintains metadata about the active swarm, recording which peers are currently seeding or leeching the file. When a new client joins, the tracker supplies a list of IP addresses of available peers to establish direct connections.
(b) The original file is divided into uniform, smaller chunks (pieces), with their corresponding hash values provided in the torrent descriptor file. The client requests distinct pieces concurrently across multiple connected peers. Once all pieces are downloaded and validated against their hashes, the client joins them together in the original sequence.
评分标准
(a) 1 mark per point to max 2: - Maintains a list / registry of active peers / swarm sharing the file. [1] - Supplies IP addresses / connection details of available peers to clients joining the swarm. [1] - Does NOT store or transmit the actual file data. [1]
(b) 1 mark per point to max 2: - The target file is divided into smaller chunks / pieces / segments. [1] - The client downloads different chunks simultaneously / in parallel from multiple peers. [1] - Pieces are verified (using hashes) and reassembled / concatenated in the correct order to recreate the complete file. [1]
题目 5 · short_answer
4 分
A high-performance computing system uses a Reduced Instruction Set Computer (RISC) processor that supports instruction pipelining.
(a) State two architectural differences between a RISC processor and a Complex Instruction Set Computer (CISC) processor. [2]
(b) Explain how instruction pipelining increases processor performance, and identify one condition that causes the pipeline to stall. [2]
查看答案详解收起答案详解
解题
(a) Key architectural differences include: - Instruction simplicity: RISC uses fewer, simpler, fixed-format instructions executed in single cycles; CISC instructions are variable in format and can take multiple clock cycles. - Memory access: RISC employs a strict load/store architecture where arithmetic operations operate only on registers; CISC permits operations directly on memory addresses. - Hardware vs Microcode: RISC utilizes hardwired control units; CISC uses microprogrammed control logic. - Register availability: RISC typically features a larger number of general-purpose registers compared to CISC.
(b) Pipelining enables simultaneous processing of different instruction phases (e.g., fetching instruction \(n+2\), decoding instruction \(n+1\), and executing instruction \(n\)), significantly increasing instruction throughput per clock cycle. A pipeline stall (or flush) occurs when execution must wait, such as during a conditional branch where target instructions cannot be predicted (control hazard) or when an instruction requires an uncomputed result from a preceding instruction (data hazard).
评分标准
(a) 1 mark per distinct valid difference (max 2): - RISC has fewer / simpler instructions // CISC has more / complex instructions. [1] - RISC instructions have a fixed length / execute in one cycle // CISC instructions have variable length / take multiple cycles. [1] - RISC only allows memory access via LOAD / STORE (load-store architecture) // CISC allows direct memory manipulation within arithmetic/logic instructions. [1] - RISC relies on a hardwired control unit // CISC relies on microprogramming / microcode. [1] - RISC has more general-purpose registers // CISC has fewer general-purpose registers. [1]
(b) 1 mark for performance explanation + 1 mark for valid cause of stall: - Performance: Overlaps stages of the Fetch-Execute cycle for different instructions concurrently, increasing throughput / instructions completed per unit time. [1] - Cause of stall: Branch / jump instruction (control hazard / unexpected branch) // Data dependency / data hazard (instruction depends on the result of an earlier uncompleted instruction) // Structural hazard (resource conflict / simultaneous hardware access). [1]
题目 6 · theory
9 分
A logic circuit has four inputs: \(A\), \(B\), \(C\), and \(D\). The output \(X\) is represented by the following Boolean expression:
(b) (i) Identify the minimum number of groups of 1s required to produce an optimal sum-of-products expression, and describe each group by specifying its size and the cell coordinates (in the form \(AB, CD\)) contained within it. [2]
(ii) Write the simplified sum-of-products Boolean expression derived from your groups in part (b)(i). [2]
(c) State two benefits of using a Karnaugh map rather than Boolean algebra identities to simplify logic expressions. [2]
查看答案详解收起答案详解
解题
(a) Identifying minterms/cells from the given terms: - \(\overline{A}\,\overline{B}D\) covers \(AB=00\), \(CD=01\) and \(AB=00\), \(CD=11\). - \(AB\overline{C}\) covers \(AB=11\), \(CD=00\) and \(AB=11\), \(CD=01\). - \(\overline{A}CD\) covers \(AB=00\), \(CD=11\) and \(AB=01\), \(CD=11\). - \(B\overline{C}D\) covers \(AB=01\), \(CD=01\) and \(AB=11\), \(CD=01\).
(b) (i) Two groups are needed: - Group 1 (size 4): a \(2 \times 2\) quad consisting of cells \((00, 01)\), \((00, 11)\), \((01, 01)\), and \((01, 11)\). - Group 2 (size 2): a pair consisting of cells \((11, 00)\) and \((11, 01)\).
(ii) Simplification: - From Group 1: \(A=0\) (constant), \(B\) changes \(0 \to 1\), \(C\) changes \(0 \to 1\), \(D=1\) (constant) \(\implies \overline{A}D\). - From Group 2: \(A=1\), \(B=1\), \(C=0\) (constant), \(D\) changes \(0 \to 1\) \(\implies AB\overline{C}\). Combined simplified expression: \(X = \overline{A}D + AB\overline{C}\) (or \(\text{NOT } A \text{ AND } D \text{ OR } A \text{ AND } B \text{ AND NOT } C\)).
(c) Benefits of Karnaugh maps: 1. Visual pattern recognition makes it easier and faster to spot simplifications compared to lengthy algebraic manipulation. 2. Less prone to missing common terms or making arithmetic/algebraic rule errors. 3. Guarantees the minimal sum-of-products form if standard grouping rules (powers of 2, largest possible groups) are strictly followed.
评分标准
(a) 1 mark for each correctly populated row pair: - Row 00 (0, 1, 1, 0) and Row 01 (0, 1, 1, 0) correct [1] - Row 11 (1, 1, 0, 0) and Row 10 (0, 0, 0, 0) correct [1] - All remaining empty cells explicitly filled with 0s (no blank cells) [1]
(b) (i) - Group 1 correctly identified as a group of 4 covering \((00,01), (00,11), (01,01), (01,11)\) [1] - Group 2 correctly identified as a group of 2 covering \((11,00), (11,01)\) [1]
(ii) - \(\overline{A}D\) derived correctly from the 4-cell group [1] - \(AB\overline{C}\) derived correctly from the 2-cell group and combined using OR [1] (Allow FT from candidate's groups in (b)(i))
(c) 1 mark per valid benefit (max 2): - Visual method / easier to see common patterns/groupings - Less chance of errors compared to multi-step algebraic manipulation - Systematically leads to the most minimal SOP form
题目 7 · theory
9 分
(a) Convert the following infix expression into Reverse Polish Notation (RPN):
$$ (a + b \times c) / (d - e + f) $$
Assume standard operator precedence, where addition and subtraction evaluate from left to right.
[2]
(b) State two reasons why compilers convert mathematical expressions into Reverse Polish Notation before generating executable code.
### Part (a) 1. Convert numerator $(a + b \times c)$: - Multiplication has higher precedence: $b \times c \rightarrow b\ c\ *$ - Addition with $a$: $a + (b \times c) \rightarrow a\ b\ c\ *\ +$ 2. Convert denominator $(d - e + f)$: - Left-associative: $(d - e) + f$ - First operation: $d - e \rightarrow d\ e\ -$ - Second operation: $(d - e) + f \rightarrow d\ e\ -\ f\ +$ 3. Combine with division $/$ - $(a + b \times c) / (d - e + f) \rightarrow a\ b\ c\ *\ +\ d\ e\ -\ f\ +\ /$
### Part (b) Two reasons include: - RPN is unambiguous and does not require brackets/parentheses. - No need to maintain or check operator precedence during runtime evaluation. - It can be evaluated easily and efficiently in a single linear pass using a simple stack mechanism.
### Part (c)(ii) The value remaining at the top of the stack is 36.
评分标准
(a) - `a b c * +` correctly converted (1 mark) - `d e - f + /` correctly converted and combined (1 mark)
(Total: 2 marks)
(b) Award 1 mark per valid point (Max 2): - No brackets / parentheses are needed to dictate evaluation order (1) - Expressions are unambiguous (1) - Can be evaluated in a single pass / left-to-right (1) - Operator precedence rules are inherently built into the expression / do not need to be calculated at execution time (1) - Evaluation maps directly and simply onto hardware/stack architectures (1)
(c)(ii) - `36` (Allow FT from incorrect stack calculation if arithmetic was followed consistently) (1 mark)
(Total: 1 mark)
题目 8 · theory
6 分
A software company, DevCorp, distributes automated firmware updates to thousands of client devices over the internet. DevCorp produces a digital signature for each firmware update file before distribution.
(a) Explain why symmetric key encryption is not suitable for verifying that the update was authored specifically by DevCorp. [2]
(b) Describe how DevCorp generates the digital signature for the firmware update file. [2]
(c) Describe the steps taken by a client device to verify the digital signature upon receiving the firmware update file. [2]
查看答案详解收起答案详解
解题
(a) - In symmetric key cryptography, the same secret key is used for both encryption and decryption, requiring it to be shared with every client. - Because all clients would possess the secret key, any client (or intercepted party) could produce valid encrypted files claiming to be DevCorp, preventing true authenticity and non-repudiation.
(b) 1. A cryptographic hash function (e.g. SHA-256) is applied to the firmware update file to generate a fixed-length hash value (message digest). 2. The resulting hash value is encrypted using DevCorp's private key to produce the digital signature.
(c) 1. The client decrypts the digital signature using DevCorp's public key to recover the original hash value. 2. The client runs the same cryptographic hash function on the received firmware file to produce a new hash value. 3. The client compares both hash values; if they match, it confirms the update is authentic (came from DevCorp) and has not been altered in transit.
评分标准
(a) 1 mark per point to max 2: - Symmetric encryption uses a single / shared key for both encryption and decryption. - The key would need to be distributed to / stored on all client devices // many parties have the key. - Any client / third party possessing the key could forge updates / tamper with data and claim it came from DevCorp // cannot provide non-repudiation / proof of authenticity.
(b) 1 mark per point to max 2: - A hashing algorithm / hash function is applied to the firmware file to produce a hash value / message digest. - The hash value / message digest is encrypted using DevCorp's private key.
(c) 1 mark per point to max 2: - The digital signature is decrypted using DevCorp's public key (to retrieve the decrypted hash value). - The client applies the same hashing algorithm to the received firmware file to generate a new hash value, and compares the two hash values (a match verifies integrity and authenticity).
题目 9 · theory
9 分
An autonomous mobile robot in an automated fulfillment center uses pathfinding algorithms and machine learning to navigate and recognise obstacles.
(a) (i) State what is meant by a heuristic in the context of the A* search algorithm. [1]
(ii) Explain the difference between Dijkstra's algorithm and the A* search algorithm when determining the shortest path between a start node and a goal node. [2]
(b) The robot is currently exploring paths on a weighted grid. The A* algorithm evaluates candidate nodes using the function:
\[ f(n) = g(n) + h(n) \]
The open list currently contains three unexplored nodes with the following values:
State which node the A* algorithm will expand next. Justify your answer showing all calculations. [2]
(c) The robot uses an Artificial Neural Network (ANN) to classify obstacles detected by its camera.
(i) Describe the role of back propagation of errors in training an Artificial Neural Network. [2]
(ii) Contrast supervised learning and unsupervised learning in the context of machine learning. [2]
查看答案详解收起答案详解
解题
(a) (i) A heuristic is an estimate, informed guess, or problem-specific approximation of the remaining distance or cost from a current node to the destination/goal node.
(ii) - Dijkstra's algorithm considers only the cumulative path cost from the start node (i.e. \(g(n)\)) to every node, expanding uniformly in all directions. - A* search incorporates a heuristic estimate of the remaining cost to the goal (i.e. \(h(n)\)) in addition to the path cost from the start (\(f(n) = g(n) + h(n)\)), allowing it to focus the search directly towards the target node and typically explore fewer nodes.
Node to expand next: Node R Justification: Node R has the lowest total evaluation function value (\(f(R) = 15\)), so A* prioritises it for expansion.
(c) (i) 1. The network computes the difference/error between the predicted output and the expected target output at the output layer. 2. This error value is propagated backward through the hidden layers, and mathematical optimisation (such as gradient descent) is used to iteratively update/adjust the weights and biases of the connections to minimise future error.
(ii) - Supervised learning: The model is trained using labelled data (inputs paired with known target outputs); the model learns a mapping function to predict outcomes for new inputs. - Unsupervised learning: The model is provided with unlabelled data without target outputs; the algorithm discovers intrinsic patterns, structures, groupings, or clusters on its own.
评分标准
(a)(i) 1 mark for: - An estimate / approximation / rule of thumb of the cost or distance from the current node to the goal/destination node.
(a)(ii) 1 mark per point to max 2: - Dijkstra's algorithm uses only the actual/accumulated path cost from the start node / does not use a heuristic / expands uniformly. - A* uses both the cost from start and a heuristic estimate to the goal / uses \(f(n) = g(n) + h(n)\) to guide/direct the search towards the goal.
(b) 1 mark for: - Correct calculation of \(f(n)\) for all three nodes: \(f(P) = 17\), \(f(Q) = 16\), \(f(R) = 15\). 1 mark for: - Identifying Node R with the justification that it has the lowest \(f(n)\) / total estimated cost.
(c)(i) 1 mark per point to max 2: - Calculates the error/difference between the actual/calculated output and the expected/target output. - Propagates this error backwards through the network layers to adjust/update weights (and biases) to minimise the error.
(c)(ii) 1 mark per point to max 2: - Supervised learning uses labelled data / known input-output pairs. - Unsupervised learning uses unlabelled data / finds patterns, clusters, or relationships without predefined target outputs.
题目 10 · theory
9 分
(a) An insertion sort algorithm is used to sort a 1D array of \(n\) integer elements.
(i) State the time complexity of the insertion sort algorithm using Big O notation for:
• the worst case • the best case [2]
(ii) Explain why the insertion sort algorithm achieves this best-case time complexity when the elements in the array are already sorted in the required order. [2]
(b) An array `Scores` contains `NumScores` integer elements, indexed from 1 to `NumScores`.
Write pseudocode for a procedure `InsertionSort` that sorts the elements of `Scores` into descending order.
• The array `Scores` must be passed by reference. • The integer `NumScores` must be passed by value. [5]
查看答案详解收起答案详解
解题
### Part (a)(i) - Worst-case time complexity: \(O(n^2)\) - Best-case time complexity: \(O(n)\)
### Part (a)(ii) When the array is already sorted: 1. Each element only needs to be compared once with its predecessor because the inner loop condition `Scores[Position] < CurrentValue` (or corresponding condition) is immediately false on the first comparison. 2. No shifts are performed within the inner loop, meaning the algorithm only executes the outer loop \(n - 1\) times, resulting in a linear runtime proportional to \(n\).
### Part (b) ```text PROCEDURE InsertionSort(BYREF Scores : ARRAY, BYVAL NumScores : INTEGER) DECLARE Index : INTEGER DECLARE CurrentValue : INTEGER DECLARE Position : INTEGER
FOR Index <- 2 TO NumScores CurrentValue <- Scores[Index] Position <- Index - 1 WHILE Position >= 1 AND Scores[Position] < CurrentValue Scores[Position + 1] <- Scores[Position] Position <- Position - 1 ENDWHILE Scores[Position + 1] <- CurrentValue NEXT Index ENDPROCEDURE ```
评分标准
(a)(i) [2 marks] - 1 mark: Worst case is \(O(n^2)\) / \(O(N^2)\) - 1 mark: Best case is \(O(n)\) / \(O(N)\)
(a)(ii) [2 marks, 1 mark per point up to max 2] - MP1: Only one comparison is made per element / the inner condition is evaluated as false on the first check. - MP2: No elements need to be shifted / the outer loop executes \(n-1\) times giving a linear relation.
(b) [5 marks] - MP1: Correct `PROCEDURE` header with parameter identifiers and correct parameter modes (`BYREF Scores` and `BYVAL NumScores`) and `ENDPROCEDURE`. - MP2: Outer loop traversing from index 2 to `NumScores` (or index 1 to `NumScores - 1` if 0-indexed). - MP3: Storing current value into a temporary variable/key and initialising `Position` to `Index - 1`. - MP4: `WHILE` loop containing both the lower-boundary condition (`Position >= 1`) AND the correct descending comparison (`Scores[Position] < CurrentValue`). - MP5: Correct shifting of array elements (`Scores[Position + 1] <- Scores[Position]`), decrementing `Position`, and inserting `CurrentValue` at `Scores[Position + 1]` after the while loop.
题目 11 · free-text
8 分
An art gallery maintains information about paintings, painters, and exhibition locations using a declarative programming language.
The knowledge base contains the following clauses:
(a) Write a clause to add a new fact that the artwork the_transfiguration was created by raphael in the year 1520. [1]
(b) (i) State the output produced by the query: artwork(Title, picasso, 1937). [2]
(ii) Identify what type of element Title represents in this declarative language program. [1]
(c) An artwork is classified as twentieth-century if its year of creation is between 1901 and 2000 inclusive. Write a rule twentieth_century(ArtName) that is true if ArtName was produced in the twentieth century. [2]
(d) Write a rule shared_room(Art1, Art2) that is true if Art1 and Art2 are different artworks displayed in the same room. [2]
查看答案详解收起答案详解
解题
(a) artwork(the_transfiguration, raphael, 1520).
(b) (i) The query searches the artwork/3 facts where the artist is picasso and year is 1937. The matching titles are guernica (line 05) and weeping_woman (line 07). Output: Title = guernica, Title = weeping_woman. (ii) Variable (indicated by initial capital letter).
(c) twentieth_century(ArtName) :- artwork(ArtName, Artist, Year), Year >= 1901, Year <= 2000. (or using anonymous variable _ for Artist, and =< for Prolog syntax).
(d) shared_room(Art1, Art2) :- room(R, Art1), room(R, Art2), Art1 \= Art2. (checks both artworks are associated with the same room variable R and ensures Art1 and Art2 are distinct).
评分标准
(a) 1 mark for correct predicate and arguments: artwork(the_transfiguration, raphael, 1520).
(b) (i) 1 mark for Title = guernica, 1 mark for Title = weeping_woman. (ii) 1 mark for Variable.
(c) 1 mark for correct head and artwork lookup: twentieth_century(ArtName) :- artwork(ArtName, _, Year) (or with named artist variable). 1 mark for correct range condition: Year >= 1901, Year <= 2000 (or Year > 1900, Year < 2001, or Prolog =< syntax).
(d) 1 mark for checking both artworks are in the same room: room(R, Art1), room(R, Art2). 1 mark for checking that Art1 and Art2 are different: Art1 \= Art2 (accept Art1 <> Art2 / Art1 != Art2 / NOT(Art1 = Art2)).
Paper 41 (Practical Programming)
Perform all tasks using Python, VB.NET, or Java in console mode. Paste code and execution screenshots into evidence document.
3 题目 · 75 分
题目 1 · problem_solving
26 分
A logistics warehouse manages parcel dispatches using a linear queue. The queue stores parcel tracking codes (strings) and has a maximum capacity of 8 items.
The queue is implemented using a 1D array named `ParcelQueue` of type `STRING` with index bounds 0 to 7.
Two integer pointer variables are used: * `HeadPointer` points to the index of the first parcel to be removed. * `TailPointer` points to the index where the next parcel will be inserted.
(a) Write program code to: * declare the global 1D array `ParcelQueue` to hold 8 strings, initialized with empty strings `""` * declare `HeadPointer` and initialize it to `-1` * declare `TailPointer` and initialize it to `0`.
Save your program. [4]
(b) Write a function `Enqueue` that: * takes the tracking code to be added as a string parameter * checks whether the queue is full (i.e. `TailPointer` has reached 8) * if the queue is full, outputs `"Queue is full. Cannot add parcel."` and returns `FALSE` * if the queue is not full: * if `HeadPointer` is `-1`, sets `HeadPointer` to `0` * inserts the tracking code at index `TailPointer` in `ParcelQueue` * increments `TailPointer` by 1 * returns `TRUE`.
Save your program. [6]
(c) Write a function `Dequeue` that: * checks whether the queue is empty (i.e. `HeadPointer` is `-1` or `HeadPointer` equals `TailPointer`) * if the queue is empty, outputs `"Queue is empty. No parcel to dispatch."` and returns an empty string `""` * if the queue is not empty: * retrieves the parcel tracking code at `HeadPointer` * replaces the item at `HeadPointer` in `ParcelQueue` with `""` * increments `HeadPointer` by 1 * returns the retrieved tracking code.
Save your program. [5]
(d) Write a procedure `DisplayQueue` that outputs the current state of the queue: * outputs the values of `HeadPointer` and `TailPointer` * outputs all elements currently in the queue from index `0` to `7` along with their index numbers.
Save your program. [4]
(e) (i) Write the main program code to perform the following operations in order: 1. Call `DisplayQueue`. 2. Attempt to enqueue the following five parcel tracking codes: `"PK-101"`, `"PK-102"`, `"PK-103"`, `"PK-104"`, `"PK-105"`. For each item, output an appropriate message indicating whether it was successfully enqueued or not. 3. Call `DisplayQueue`. 4. Call `Dequeue` twice, outputting the dispatched tracking code returned each time. 5. Call `DisplayQueue`. 6. Attempt to enqueue four more parcel tracking codes: `"PK-106"`, `"PK-107"`, `"PK-108"`, `"PK-109"`, outputting the result of each attempt. 7. Call `DisplayQueue`.
Save your program. [5]
(ii) Test your program by running the main program. Take a screenshot of the console output and paste it into your evidence document. [2]
查看答案详解收起答案详解
解题
### Python 3 Solution
```python # Global declarations ParcelQueue = ["" for _ in range(8)] HeadPointer = -1 TailPointer = 0
def Enqueue(tracking_code): global HeadPointer, TailPointer, ParcelQueue if TailPointer >= 8: print("Queue is full. Cannot add parcel.") return False
def Dequeue(): global HeadPointer, TailPointer, ParcelQueue if HeadPointer == -1 or HeadPointer == TailPointer: print("Queue is empty. No parcel to dispatch.") return ""
def DisplayQueue(): global HeadPointer, TailPointer, ParcelQueue print(f"HeadPointer: {HeadPointer}, TailPointer: {TailPointer}") print("Queue contents:") for i in range(8): val = ParcelQueue[i] if ParcelQueue[i] != "" else "" print(f" Index {i}: {val}") print("-" * 30)
def main(): print("--- Initial Queue State ---") DisplayQueue()
# Enqueue 5 items batch1 = ["PK-101", "PK-102", "PK-103", "PK-104", "PK-105"] for code in batch1: if Enqueue(code): print(f"Enqueued: {code}") else: print(f"Failed to enqueue: {code}")
print(" --- After 5 Enqueues ---") DisplayQueue()
# Dequeue 2 items for _ in range(2): dispatched = Dequeue() if dispatched != "": print(f"Dispatched parcel: {dispatched}")
print(" --- After 2 Dequeues ---") DisplayQueue()
# Enqueue 4 items (tests overflow condition on linear queue) batch2 = ["PK-106", "PK-107", "PK-108", "PK-109"] for code in batch2: if Enqueue(code): print(f"Enqueued: {code}") else: print(f"Failed to enqueue: {code}")
print(" --- Final Queue State ---") DisplayQueue()
if __name__ == "__main__": main() ```
### Expected Console Output: ```text --- Initial Queue State --- HeadPointer: -1, TailPointer: 0 Queue contents: Index 0: Index 1: Index 2: Index 3: Index 4: Index 5: Index 6: Index 7: ------------------------------ Enqueued: PK-101 Enqueued: PK-102 Enqueued: PK-103 Enqueued: PK-104 Enqueued: PK-105
--- After 5 Enqueues --- HeadPointer: 0, TailPointer: 5 Queue contents: Index 0: PK-101 Index 1: PK-102 Index 2: PK-103 Index 3: PK-104 Index 4: PK-105 Index 5: Index 6: Index 7: ------------------------------ Dispatched parcel: PK-101 Dispatched parcel: PK-102
--- After 2 Dequeues --- HeadPointer: 2, TailPointer: 5 Queue contents: Index 0: Index 1: Index 2: PK-103 Index 3: PK-104 Index 4: PK-105 Index 5: Index 6: Index 7: ------------------------------ Enqueued: PK-106 Enqueued: PK-107 Enqueued: PK-108 Queue is full. Cannot add parcel. Failed to enqueue: PK-109
--- Final Queue State --- HeadPointer: 2, TailPointer: 8 Queue contents: Index 0: Index 1: Index 2: PK-103 Index 3: PK-104 Index 4: PK-105 Index 5: PK-106 Index 6: PK-107 Index 7: PK-108 ------------------------------ ```
评分标准
Part (a) [4 marks] * 1 mark: Declaring 1D array `ParcelQueue` of length 8 with string data type. * 1 mark: Initializing all 8 array elements to empty strings `""`. * 1 mark: Declaring `HeadPointer` initialized to `-1`. * 1 mark: Declaring `TailPointer` initialized to `0`.
Part (b) [6 marks] * 1 mark: Function header taking one string parameter and accessing global variables. * 1 mark: Checking if queue is full (`TailPointer == 8` or `TailPointer >= 8`). * 1 mark: Outputting error message and returning `FALSE` when full. * 1 mark: Updating `HeadPointer` to `0` if `HeadPointer == -1`. * 1 mark: Storing the tracking code at `ParcelQueue[TailPointer]` and incrementing `TailPointer`. * 1 mark: Returning `TRUE` on successful enqueue.
Part (c) [5 marks] * 1 mark: Function header taking no parameters and accessing globals. * 1 mark: Checking for queue empty condition (`HeadPointer == -1` OR `HeadPointer == TailPointer`). * 1 mark: Outputting empty message and returning `""` when empty. * 1 mark: Retrieving item from `ParcelQueue[HeadPointer]` and clearing array slot (setting to `""`). * 1 mark: Incrementing `HeadPointer` and returning the retrieved item.
Part (d) [4 marks] * 1 mark: Procedure header for `DisplayQueue`. * 1 mark: Outputting the current values of `HeadPointer` and `TailPointer`. * 1 mark: Loop iterating through all indices from 0 to 7. * 1 mark: Outputting each index number alongside its array element.
Part (e)(i) [5 marks] * 1 mark: Calling `DisplayQueue` at the start. * 1 mark: Iterating/enqueuing the first batch of 5 codes (`"PK-101"` to `"PK-105"`) with appropriate status messages. * 1 mark: Calling `Dequeue` twice and outputting the dispatched tracking codes. * 1 mark: Attempting to enqueue the second batch of 4 codes (`"PK-106"` to `"PK-109"`) with status messages. * 1 mark: Calling `DisplayQueue` at the required stages in the process.
Part (e)(ii) [2 marks] * 1 mark: Screenshot shows correct output for initial queue, first batch enqueues, and two dequeues. * 1 mark: Screenshot shows correct queue full message for `"PK-109"` and final state with `HeadPointer = 2` and `TailPointer = 8`.
题目 2 · essay
28 分
A logistics and delivery tracking system stores information about parcel consignments.
A text file named `Consignments.txt` contains records of up to 50 consignments. Each consignment has four data items stored on separate lines in the following order: - Tracking Code (string, e.g., `"TRK1024"`) - Destination City (string, e.g., `"Manchester"`) - Weight (real number in kilograms, e.g., `14.5`) - Priority Level (integer: 1 for Standard, 2 for Express, 3 for Urgent)
An example of the data for one consignment in `Consignments.txt` is: ``` TRK1024 Manchester 14.5 3 ```
(a) Write program code to define a class `Consignment` with the following private attributes and public methods:
Methods: - `__init__()` / `Constructor` : takes `TrackingCode`, `Destination`, `Weight`, and `Priority` as parameters and assigns them to the class attributes. - `GetTrackingCode()` : returns the tracking code. - `GetDestination()` : returns the destination city. - `GetWeight()` : returns the weight. - `GetPriority()` : returns the priority level. - `CalculateFee()` : calculates and returns the shipping fee (REAL) based on: - Base rate: $5.00 per kg of weight. - A surcharge based on priority: - Priority 1 (Standard): no surcharge. - Priority 2 (Express): additional 25% on top of the calculated weight base cost. - Priority 3 (Urgent): additional 60% on top of the calculated weight base cost.
Save your program code.
[7]
(b) In the main program: - Declare a global 1D array named `ConsignmentList` capable of holding up to 50 `Consignment` objects. - Declare a global integer variable `ConsignmentCount` and initialise it to 0. - Write a function `ReadData()` that: - Opens `Consignments.txt` in read mode. - Uses exception handling to trap any file opening errors. - If the file cannot be opened, outputs a suitable error message and returns `False`. - If the file is opened successfully, reads each consignment record, instantiates a new `Consignment` object, and appends/stores it in `ConsignmentList`. - Updates `ConsignmentCount` with the total number of records loaded. - Closes the file and returns `True`.
Save your program code.
[8]
(c) Write a procedure `FilterAndDisplay()` that: - Takes two parameters: a string `TargetCity` and a real number `MaxFee`. - Iterates through the stored objects in `ConsignmentList`. - Identifies and outputs the tracking code, weight, and calculated fee of all consignments destined for `TargetCity` whose calculated fee is less than or equal to `MaxFee`. - Counts how many consignments meet the criteria. - If no consignments match the criteria, outputs a message `"No matching consignments found."`; otherwise, outputs the total count of matched consignments.
Save your program code.
[6]
(d) (i) Write code for the main program to: - Call `ReadData()` and verify it loaded data successfully. - Prompt the user to enter a destination city and a maximum allowable fee. - Call `FilterAndDisplay()` passing the user input values.
Save your program code.
[4]
(d) (ii) Test your program by: - Creating the file `Consignments.txt` containing the following test data: ``` TRK1024 Manchester 14.5 3 TRK2048 London 8.0 1 TRK3012 Manchester 6.0 2 TRK4190 Birmingham 22.0 1 TRK5501 Manchester 25.0 3 ``` - Running the program with the input destination `"Manchester"` and maximum fee `50.0`. - Take a screenshot showing the console output and paste it into your evidence document.
# Main Program Execution if __name__ == "__main__": if ReadData(): print(f"Successfully loaded {ConsignmentCount} records.") city_input = input("Enter destination city: ").strip() max_fee_input = float(input("Enter maximum fee: ")) FilterAndDisplay(city_input, max_fee_input) ```
### Output for test run with destination 'Manchester' and Max Fee 50.0: ``` Successfully loaded 5 records. Enter destination city: Manchester Enter maximum fee: 50.0 Tracking Code: TRK3012, Weight: 6.0 kg, Fee: $37.50 Total matched consignments: 1 ```
评分标准
(a) Class Definition [7 marks] - `MP1`: Class header and private attributes initialised in constructor. - `MP2`: Four constructor parameters correctly passed and stored. - `MP3`: Getter methods for all 4 attributes implemented returning correct values. - `MP4`: `CalculateFee()` calculates base cost as `Weight * 5.0`. - `MP5`: Correct branch / logic for priority 2 surcharge (+25% / `* 1.25`). - `MP6`: Correct branch / logic for priority 3 surcharge (+60% / `* 1.60`). - `MP7`: Priority 1 returns base cost directly (or handles invalid/default priority).
(b) File Processing & Global Array [8 marks] - `MP1`: Global array `ConsignmentList` declared with length 50 AND `ConsignmentCount` initialised to 0. - `MP2`: `ReadData()` header and `try ... except / catch` file opening structure. - `MP3`: Correct error message printed and returns `False` on file error. - `MP4`: Loop until EOF / all 4 lines per record read sequentially. - `MP5`: Casting/converting `Weight` to float/real and `Priority` to integer. - `MP6`: Instantiating `Consignment` object with 4 read values. - `MP7`: Storing object in array at index `ConsignmentCount` and incrementing `ConsignmentCount`. - `MP8`: Closing the file and returning `True` upon successful completion.
(c) Filtering Procedure [6 marks] - `MP1`: Procedure header with 2 parameters (`TargetCity`, `MaxFee`). - `MP2`: Loop through `ConsignmentList` from index 0 to `ConsignmentCount - 1`. - `MP3`: Selection condition comparing destination against `TargetCity`. - `MP4`: Selection condition checking if `CalculateFee() <= MaxFee`. - `MP5`: Outputting `TrackingCode`, `Weight`, and fee for matching items. - `MP6`: Counting matches and outputting error message if 0 or total count if >= 1.
(d) Main Program & Testing [7 marks] - (d)(i) [4 marks] - `MP1`: Call to `ReadData()`. - `MP2`: Checking return value of `ReadData()` before continuing. - `MP3`: Prompting and reading user inputs for city and fee with appropriate types. - `MP4`: Calling `FilterAndDisplay()` passing both input values. - (d)(ii) [3 marks] - `MP1`: Evidence screenshot showing console input. - `MP2`: Console output showing record `TRK3012` with fee `$37.50` (or `37.5`). - `MP3`: Console output showing matched count of `1` (and `TRK1024` fee $116.00 / `TRK5501` fee $200.00 excluded).
题目 3 · structured
21 分
A logistics firm manages standard parcels and express parcels.
(a) The class `Parcel` has the following private attributes and public methods:
* Attributes: * `TrackingCode` : STRING * `Weight` : REAL * `Status` : STRING * Methods: * `Constructor(TrackingCode, Weight)` : initialises `TrackingCode` and `Weight` with parameters, and sets `Status` to `"Pending"` * `GetTrackingCode()` : returns `TrackingCode` * `GetWeight()` : returns `Weight` * `GetStatus()` : returns `Status` * `SetStatus(NewStatus)` : updates `Status` with `NewStatus` * `CalculateCost()` : returns a REAL value calculated as `Weight * 2.50`
Write program code for the class `Parcel`.
Save your program. [6]
(b) The child class `ExpressParcel` inherits from the class `Parcel`. It has the following additional private attributes and public methods:
* Attributes: * `GuaranteedDays` : INTEGER * `PriorityLevel` : STRING * Methods: * `Constructor(TrackingCode, Weight, GuaranteedDays, PriorityLevel)` : initialises the inherited attributes using the parent constructor and initialises `GuaranteedDays` and `PriorityLevel` * `GetPriorityLevel()` : returns `PriorityLevel` * `CalculateCost()` : overrides the parent method. The cost is the base cost calculated by the parent method plus an extra fee: if `GuaranteedDays` is 1, the extra fee is `15.00`; otherwise the extra fee is `8.00`. Returns the total cost as a REAL.
Write program code for the class `ExpressParcel`.
Save your program. [5]
(c) Write program code for a procedure `DisplaySummary(ParcelArray, NumberOfParcels)` that: * takes an array of type `Parcel` (or generic object type in Python) and the integer number of items currently stored as parameters * loops through each parcel in the array * outputs the `TrackingCode`, `Weight`, `Status`, and total cost (using `CalculateCost()`) for each parcel in a readable format.
Save your program. [4]
(d) (i) Write program code for the main program that: * declares a 1D array `ParcelList` capable of holding 10 objects of type `Parcel` * creates two instances of `Parcel` and two instances of `ExpressParcel` with the following data and stores them in `ParcelList`: 1. `Parcel`: TrackingCode `"TRK101"`, Weight `3.5` 2. `Parcel`: TrackingCode `"TRK102"`, Weight `1.2` 3. `ExpressParcel`: TrackingCode `"EXP501"`, Weight `4.0`, GuaranteedDays `1`, PriorityLevel `"High"` 4. `ExpressParcel`: TrackingCode `"EXP502"`, Weight `2.5`, GuaranteedDays `2`, PriorityLevel `"Medium"` * calls `DisplaySummary` to display all 4 parcels * uses `SetStatus()` on the parcel with tracking code `"TRK101"` to change its status to `"Dispatched"` * calls `DisplaySummary` again to display the updated information.
Save your program. [4]
(ii) Test your program.
Take a screenshot of the console output and paste it into your Evidence Document. [2]
#### (a) Class `Parcel` [Max 6 marks] * MP1: Class header and constructor header with parameters `TrackingCode` and `Weight`. * MP2: `TrackingCode`, `Weight`, and `Status` declared as private attributes. * MP3: Constructor assigns parameter values to `TrackingCode` and `Weight`, and initialises `Status` to `"Pending"`. * MP4: Getter methods `GetTrackingCode()`, `GetWeight()`, and `GetStatus()` returning appropriate attributes. * MP5: Setter method `SetStatus(NewStatus)` correctly updating `Status`. * MP6: Method `CalculateCost()` returning `Weight * 2.50` (or equivalent calculation).
#### (b) Class `ExpressParcel` [Max 5 marks] * MP7: Class header inheriting from `Parcel`. * MP8: Constructor calling parent constructor with `TrackingCode` and `Weight`. * MP9: Initialising private attributes `GuaranteedDays` and `PriorityLevel`. * MP10: Getter method `GetPriorityLevel()` returning `PriorityLevel`. * MP11: Method `CalculateCost()` calling parent `CalculateCost()` / recalculating base cost and adding `15.00` if `GuaranteedDays == 1` else adding `8.00`.
#### (c) Procedure `DisplaySummary` [Max 4 marks] * MP12: Procedure header taking array and integer count as parameters. * MP13: Loop iterating from `0` to `NumberOfParcels - 1` (or equivalent valid bounds). * MP14: Calls getter methods (`GetTrackingCode()`, `GetWeight()`, `GetStatus()`) and `CalculateCost()` for each element. * MP15: Outputs formatted parcel details.
#### (d)(i) Main Program Code [Max 4 marks] * MP16: Declaring 1D array of length 10 to store `Parcel` objects. * MP17: Instantiating two `Parcel` and two `ExpressParcel` objects with specified data and storing them in array. * MP18: Calling `DisplaySummary` with array and count. * MP19: Calling `SetStatus("Dispatched")` on `"TRK101"` object and calling `DisplaySummary` again.
#### (d)(ii) Evidence / Output Screenshot [Max 2 marks] * MP20: Screenshot shows all 4 parcels displayed initially with `Pending` status and correct calculated costs ($8.75, $3.00, $25.00, $14.25). * MP21: Screenshot shows second display reflecting `Dispatched` status for `TRK101` while other attributes and parcels remain intact.
想知道自己有几分把握?
thinka 是 DSE 学生在用的 AI 练习应用,提供无限量练习题、即时自动批改和详细解题步骤。超过 100,000 名学生用它确认自己是真的会,而不只是「以为会」。