Cambridge IAL · Thinka 原創模擬試題

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

Thinka Nov 2024 (V3) Cambridge International A Level-Style Mock — Computer Science (9618)

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

卷一 (Theory Fundamentals)

Answer all questions. Calculators must not be used.
9 題目 · 74.64
題目 1 · Structured
8.33
(a) An 8-bit register contains the two's complement binary number: 10110010.
Convert this number to its denary value. Show your working. [3 marks]

(b) State the main difference between how ASCII and Unicode represent characters, and explain one advantage of using Unicode. [3 marks]

(c) Describe how the sampling rate and sampling resolution affect the file size and quality of a digital audio recording. [2 marks]
查看答案詳解

解題

(a) Since the MSB is 1, the number is negative. Using binary place values (-128, 64, 32, 16, 8, 4, 2, 1), the binary pattern 10110010 corresponds to -128 + 32 + 16 + 2 = -78.

(b) ASCII uses 7 or 8 bits per character, providing a maximum of 128 or 256 unique characters. Unicode uses 16 or 32 bits, allowing for over 65,000 or billions of unique characters. This allows Unicode to represent characters from almost all global written languages, unlike ASCII.

(c) A higher sampling rate and sampling resolution capture more data points per second with greater precision, creating a digital wave closer to the original analog waveform (improving sound quality). However, storing more data points requires more bits, increasing the file size.

評分準則

(a)
- 1 mark for showing correct place values or converting bits using inversion (+1 method).
- 1 mark for adding correct active components (-128 + 32 + 16 + 2).
- 1 mark for the final correct answer: -78.

(b)
- 1 mark for stating ASCII uses 7 or 8 bits whereas Unicode uses 16 or 32 bits.
- 1 mark for stating that Unicode supports a larger character set.
- 1 mark for stating that this allows Unicode to support global languages / emojis.

(c)
- 1 mark for stating that higher sampling rate/resolution increases quality (closer to analog wave).
- 1 mark for stating that higher sampling rate/resolution increases file size (more data points/bits).
題目 2 · Structured
8.33
(a) Explain how a client-server network operates when a user requests a webpage. In your answer, refer to the role of both the client and the server. [4 marks]

(b) IP addresses are used to identify devices on a network.
(i) Describe the key differences between an IPv4 address and an IPv6 address. [2 marks]
(ii) Explain the purpose of a Subnet Mask. [2 marks]
查看答案詳解

解題

(a) The client (e.g., a web browser) initiates a connection by sending an HTTP or HTTPS request to the server, specifying the URL/resource needed. The server, which continuously listens for incoming connections, receives and processes this request, locates the requested webpage files, and sends them back as data packets. The client receives the packets and renders the webpage for the user.

(b) (i) IPv4 addresses are 32 bits long, written as four numbers separated by dots (e.g., 192.168.1.1), with limited address space. IPv6 addresses are 128 bits long, written in hexadecimal notation separated by colons, offering a vast address space to eliminate address depletion.

(ii) A subnet mask is a 32-bit value used to divide an IP address into two parts: the network address and the host address. This allows routers to determine whether the destination device is on the local network or must be sent externally.

評分準則

(a)
- 1 mark for client initiating/sending request (using browser/HTTP).
- 1 mark for server listening/processing request.
- 1 mark for server locating and transmitting webpage data packets back to client.
- 1 mark for client receiving and rendering/displaying the webpage.

(b) (i)
- 1 mark for identifying the difference in bit length (32-bit vs 128-bit).
- 1 mark for identifying format difference (dotted decimal vs hexadecimal) or address space capacity difference.

(ii)
- 1 mark for explaining that it separates network ID from host ID.
- 1 mark for explaining its role in routing decisions (identifying local vs external packets).
題目 3 · Structured
8.33
(a) Solid State Drives (SSDs) are increasingly used in modern computer systems. Describe how data is written to and read from flash memory in an SSD. [4 marks]

(b) A company is selecting storage media for two different purposes:
- Purpose 1: Distribution of a small software utility to thousands of clients at minimal cost.
- Purpose 2: Regular daily backup of 10 Terabytes of data from the main database server, where data transfer speed is critical.

Identify the most suitable storage category (magnetic, optical, or solid state) for each purpose and justify your choice. [4 marks]
查看答案詳解

解題

(a) Flash memory consists of NAND cells containing floating-gate transistors. To write data, a high voltage is applied to trap electrons in (or release them from) the floating gate through an insulating layer (tunneling), which represents binary values. To read data, a lower voltage is applied to the control gate; the presence or absence of trapped electrons dictates current flow, which the controller registers as a 0 or 1.

(b) Purpose 1: Optical (e.g., CD/DVD). Discs are extremely cheap to mass-produce and distribute physically, and being read-only ensures data cannot be modified by the client. Purpose 2: Solid State (SSD). Daily backups of 10 Terabytes require extremely high write speeds and low latency to finish within the backup window. Solid state storage offers the highest throughput compared to optical and traditional magnetic hard drives.

評分準則

(a)
- 1 mark for mentioning NAND flash memory / floating-gate transistors.
- 1 mark for explaining that high voltage traps/releases electrons (tunneling) to write data.
- 1 mark for explaining that low voltage is applied to check current flow to read data.
- 1 mark for stating that the level of charge translates to a binary 1 or 0.

(b)
- 1 mark for selecting Optical storage for Purpose 1.
- 1 mark for justifying Purpose 1 (very low unit cost for mass production/distribution, read-only benefit).
- 1 mark for selecting Solid State storage for Purpose 2.
- 1 mark for justifying Purpose 2 (highest write speed/bandwidth to process 10 TB quickly, avoiding network bottlenecks).
題目 4 · Structured
8.33
(a) Describe the role of each of the following components during the Fetch stage of the Fetch-Execute cycle:
(i) Program Counter (PC) [2 marks]
(ii) Memory Address Register (MAR) [2 marks]
(iii) Memory Data Register (MDR) [2 marks]

(b) An assembly language program uses different addressing modes. Explain the difference between immediate addressing and direct addressing. [2 marks]
查看答案詳解

解題

(a) (i) The Program Counter (PC) holds the memory address of the next instruction to be fetched. It is incremented after the address is copied to the MAR.
(ii) The Memory Address Register (MAR) receives the address from the PC and holds it temporarily so the control unit knows which address in RAM to read from/write to.
(iii) The Memory Data Register (MDR) holds the instruction or data that has just been fetched from the RAM address specified in the MAR.

(b) In immediate addressing, the operand in the assembly instruction is the actual value to be used (e.g., ADD #10 adds literal value 10 to the accumulator). In direct addressing, the operand is the memory address where the value is stored (e.g., ADD 10 adds the value stored in memory address 10).

評分準則

(a) (i)
- 1 mark for stating it holds the address of the next instruction.
- 1 mark for stating it is incremented after the address is copied to the MAR.

(a) (ii)
- 1 mark for stating it holds the address of the memory location currently being read/written.
- 1 mark for stating it receives the address from the PC.

(a) (iii)
- 1 mark for stating it holds the data/instruction fetched from RAM.
- 1 mark for stating it sits between RAM and the processor (data buffer).

(b)
- 1 mark for defining immediate addressing (operand is the literal value).
- 1 mark for defining direct addressing (operand is the memory address of the value).
題目 5 · Structured
8.33
(a) An operating system (OS) is responsible for memory management. Explain the concept of paging as a memory management technique, and describe how virtual memory uses paging when physical RAM is full. [5 marks]

(b) Translators are a type of system software. Explain the key differences between a compiler and an interpreter in terms of how they translate and execute source code. [3.33 marks]
查看答案詳解

解題

(a) Paging is a memory management technique where the physical memory (RAM) is split into equal, fixed-sized blocks called frames, and the logical memory of programs is split into blocks of the exact same size called pages. The operating system uses a Page Table to map logical pages to physical frames. When physical RAM becomes full, the OS moves inactive pages to secondary storage (virtual memory). If those pages are requested again, a page fault occurs, and the OS swaps them back into RAM, swapping out other inactive pages to free up space.

(b) A compiler translates the entire source code into machine code/object code at once, creating a standalone executable file that can run independently of the compiler. An interpreter translates and executes the source code line-by-line in real-time, requiring the interpreter program to be active during execution. Furthermore, compilers report all syntax errors at the end of translation, while interpreters halt immediately upon finding the first error.

評分準則

(a)
- 1 mark for defining physical memory split into fixed-size frames and program code into pages of the same size.
- 1 mark for mentioning the Page Table is used to map pages to physical frames.
- 1 mark for identifying that virtual memory is used when RAM is full by swapping inactive pages to secondary storage.
- 1 mark for explaining a page fault occurs when a swapped page is needed again.
- 1 mark for explaining that swapping involves moving pages between RAM and disk.

(b)
- 1 mark for stating compiler translates the entire code to machine/object code at once.
- 1 mark for stating interpreter translates and executes line-by-line.
- 1.33 marks for identifying differences in error handling (compiler reports all at end vs interpreter halts immediately) or execution independence (executable file vs interpreter overhead).
題目 6 · Structured
8.33
(a) Security threats to computer systems include malware and social engineering.
(i) Describe the difference between a virus and a worm. [2 marks]
(ii) Explain how a phishing attack is carried out and state two ways a user can identify it. [3 marks]

(b) Data integrity is vital when transmitting data. Describe how a parity block check (two-dimensional parity) can detect and correct a single-bit transmission error. [3.33 marks]
查看答案詳解

解題

(a) (i) A virus requires an existing host file or program to attach itself to and relies on human interaction (like launching the program) to execute and spread. A worm is a standalone file that self-replicates and spreads independently across network connections without any host or human interaction.

(ii) In a phishing attack, malicious actors send fraudulent emails or messages designed to mimic reputable organizations (such as banks or online stores) to trick users into clicking malicious links or submitting sensitive credentials. Users can identify phishing by looking for generic greetings, spelling/grammar mistakes, mismatched sender domains, or urgent/threatening demands for action.

(b) In a parity block check, data is arranged in a grid with parity bits calculated for both the horizontal rows and vertical columns. If a single bit is corrupted/flipped during transmission, it will cause a parity error in exactly one row and exactly one column. The receiver locates the intersection of this specific row and column to identify the exact corrupted bit, then flips it to correct the error automatically.

評分準則

(a) (i)
- 1 mark for explaining that a virus needs a host file or human intervention to run/spread.
- 1 mark for explaining that a worm is standalone and self-replicates across networks automatically.

(a) (ii)
- 1 mark for explaining the execution of phishing (sending deceptive emails imitating trusted parties to steal data).
- 2 marks for stating two distinct identification signs (generic greetings, spelling/grammatical errors, mismatched URLs, urgent demands).

(b)
- 1 mark for explaining that data is arranged in a grid of rows and columns with parity bits calculated for both.
- 1 mark for explaining that a single-bit error results in a parity error in one row and one column.
- 1.33 marks for explaining that the intersection of the failed row and column locates the error, which is corrected by flipping the bit.
題目 7 · Structured
8.33
(a) Software is distributed under various licensing models.
(i) Contrast the legal permissions and limitations of Freeware and Free Software (Open Source). [3 marks]
(ii) State the purpose of a Commercial Software Licence. [1 mark]

(b) Computer professionals often follow an ethical code of conduct. Identify two ethical principles from professional codes and explain how a software engineer applies them in practice. [4.33 marks]
查看答案詳解

解題

(a) (i) Freeware is proprietary software distributed free of charge, but its source code remains hidden, and users cannot modify or redistribute it. Free Software (Open Source) grants users the legal right to run, copy, study, modify, and redistribute the source code, often encouraging collaborative development.
(ii) A commercial software licence legally outlines how a buyer can use the software, preventing unauthorized copying, distribution, modification, or reverse-engineering, protecting the vendor's intellectual property.

(b) Principle 1: Public Interest. Software engineers must ensure that their products do not harm users or compromise public safety. This is applied by thoroughly testing safety-critical software (e.g., medical devices or flight controls) to ensure zero failures. Principle 2: Confidentiality. Professionals must protect sensitive client and user data. This is applied by implementing strong access controls and encryption, and never sharing user information without authorization.

評分準則

(a) (i)
- 1.5 marks for Freeware features (free cost, but closed source, no rights to modify/redistribute).
- 1.5 marks for Free/Open Source features (access to source code, right to study, edit, and redistribute).

(a) (ii)
- 1 mark for identifying that it protects intellectual property, restricts unauthorized distribution, or defines permitted usage limit (e.g. number of users).

(b)
- 1 mark for identifying the first correct principle (e.g. Public Interest, Professional Competence, Quality, Integrity, Confidentiality).
- 1 mark for practical application of the first principle.
- 1 mark for identifying the second correct principle.
- 1.33 marks for practical application of the second principle.
題目 8 · Structured
8.33
(a) Database designers use normalization to organize relational tables.
(i) Explain what is meant by a primary key and a foreign key. [2 marks]
(ii) Explain the characteristics of a database table that is in Second Normal Form (2NF). [2 marks]

(b) A database table named Product contains the following fields: ProductID (Primary Key), ProductName, Category, Price, and StockLevel.
Write an SQL query to retrieve the ProductName and Price of all products in the 'Electronics' category with a StockLevel greater than 50, sorted in descending order of Price. [4.33 marks]
查看答案詳解

解題

(a) (i) A primary key is a field (or combination of fields) that uniquely identifies each record/row in a database table. A foreign key is a field in one table that links to the primary key in another table, establishing a relationship between the two tables.

(ii) A table is in Second Normal Form (2NF) if it is already in First Normal Form (1NF) and does not contain any partial dependencies. This means all non-key attributes must be fully functionally dependent on the entire primary key, which is particularly relevant when a table uses a composite primary key.

(b) The SQL query is:
SELECT ProductName, Price
FROM Product
WHERE Category = 'Electronics' AND StockLevel > 50
ORDER BY Price DESC;

評分準則

(a) (i)
- 1 mark for primary key definition (unique identifier of records).
- 1 mark for foreign key definition (field linking to primary key of another table to create relationship).

(a) (ii)
- 1 mark for stating it must be in First Normal Form (1NF).
- 1 mark for defining \"no partial dependencies\" (non-key fields fully dependent on the entire composite key).

(b)
- 1 mark for correct SELECT clause: SELECT ProductName, Price.
- 1 mark for correct FROM clause: FROM Product.
- 1.33 marks for correct WHERE clause with compound condition: WHERE Category = 'Electronics' AND StockLevel > 50 (accept single or double quotes, ignore case of keywords).
- 1 mark for correct ORDER BY clause: ORDER BY Price DESC.
題目 9 · 結構題
8
**Part (a)**
An uncompressed stereo audio track is recorded with the following specifications:
- Sampling rate: \( 32,000 \text{ Hz} \)
- Sampling resolution: \( 16\text{-bit} \)
- Number of channels: \( 2 \) (stereo)
- Duration: \( 256 \text{ seconds} \)

(i) Explain what is meant by *sampling rate* and describe its effect on the accuracy of the recorded sound. (2 marks)

(ii) Calculate the file size of this recording in Mebibytes (MiB). Show your working. (3 marks)

**Part (b)**
Consider the 8-bit binary pattern representing a signed integer in two's complement: `10110100`

(i) Convert this two's complement binary number to its denary value. Show your working. (2 marks)

(ii) State the minimum and maximum denary values that can be represented using an 8-bit signed two's complement integer. (1 mark)
查看答案詳解

解題

**Part (a)(i)**
- Sampling rate is defined as the number of analog signal samples taken per second (measured in Hertz, Hz).
- Increasing the sampling rate means that the samples are taken closer together in time. This results in a digital representation that is more accurate and faithful to the original continuous analog sound wave, reducing sampling error and enabling the reproduction of higher frequencies.

**Part (a)(ii)**
- To find the total size in bits:
\( \text{Size in bits} = \text{Sampling rate} \times \text{Resolution (bits)} \times \text{Channels} \times \text{Duration (seconds)} \)
\( \text{Size in bits} = 32,000 \times 16 \times 2 \times 256 \)
- Convert bits to bytes (divide by 8):
\( \text{Size in bytes} = \frac{32,000 \times 16 \times 2 \times 256}{8} = 32,000 \times 2 \times 2 \times 256 \)
\( \text{Size in bytes} = 32,000 \times 4 \times 256 = 32,000 \times 1,024 \text{ bytes} \) (or \( 32,768,000 \text{ bytes} \))
- Convert bytes to Mebibytes (divide by \( 1024 \times 1024 \)):
\( \text{Size in MiB} = \frac{32,000 \times 1,024}{1,024 \times 1,024} = \frac{32,000}{1,024} = 31.25 \text{ MiB} \) (or \( \frac{125}{4} \text{ MiB} \))

**Part (b)(i)**
Using the binary weightings for an 8-bit signed two's complement integer (\( -128, 64, 32, 16, 8, 4, 2, 1 \)):
- Bit pattern: `1 0 1 1 0 1 0 0`
- Calculation: \( (-128 \times 1) + (64 \times 0) + (32 \times 1) + (16 \times 1) + (8 \times 0) + (4 \times 1) + (2 \times 0) + (1 \times 0) \)
- \( -128 + 32 + 16 + 4 = -76 \)
*(Alternative Method: Inverting bits of `10110100` gives `01001011`. Adding 1 gives `01001100`, which is \( 64 + 8 + 4 = 76 \) in denary. Applying the negative sign gives \( -76 \))*

**Part (b)(ii)**
- The range of an 8-bit signed two's complement integer is from \( -2^7 \) to \( +2^7 - 1 \).
- Minimum: \( -128 \)
- Maximum: \( +127 \)

評分準則

**Part (a)(i) [Max 2 marks]**
- 1 mark for defining sampling rate: The number of samples (of the sound amplitude) taken per second.
- 1 mark for explaining the effect: A higher rate means the recorded sound is more accurate / closer to the original analog waveform (accept: captures higher frequencies).

**Part (a)(ii) [Max 3 marks]**
- 1 mark for calculating the correct total bytes or bits: \( 32,768,000 \text{ bytes} \) or \( 32,000 \times 1024 \text{ bytes} \) or \( 262,144,000 \text{ bits} \).
- 1 mark for showing division by \( 1,048,576 \) (or dividing twice by \( 1024 \)).
- 1 mark for the correct final answer: \( 31.25 \text{ MiB} \) (accept equivalent fractions such as \( \frac{125}{4} \) or \( 31 \frac{1}{4} \)).

**Part (b)(i) [Max 2 marks]**
- 1 mark for evidence of correct working (e.g., showing place values \( -128 + 32 + 16 + 4 \) OR correct bit inversion and addition of 1).
- 1 mark for the correct final answer: \( -76 \).

**Part (b)(ii) [Max 1 mark]**
- 1 mark for stating both minimum: \( -128 \) and maximum: \( +127 \) correctly.

卷二 (Fundamental Problem-solving and Programming Skills)

Answer all questions. Write all programs in pseudocode or complete provided templates.
8 題目 · 74.96
題目 1 · Pseudocode Design & Structured Analysis
9.37
A text file, TransactionData.txt, stores records of transaction details. Each line of the file represents a single transaction and is structured as a comma-separated string in the format:
,,

For example: \"TX104,15,45.99\"

A function ValidateRecord(RecordStr : STRING) RETURNS BOOLEAN is required to parse a single line of text and verify that:
1. The ID is exactly 5 characters long and begins with the letters 'TX'.
2. The Quantity is a valid positive integer greater than 0.
3. The Price is a valid positive real number greater than 0.0.

Write the pseudocode for the function ValidateRecord(RecordStr : STRING) RETURNS BOOLEAN.
Assume the existence of the following built-in functions:
- LENGTH(StringVal : STRING) RETURNS INTEGER
- MID(StringVal : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING
- STRING_TO_INT(StringVal : STRING) RETURNS INTEGER
- STRING_TO_REAL(StringVal : STRING) RETURNS REAL
查看答案詳解

解題

The function begins by identifying the locations of the two commas in the input string RecordStr to split the record into three substrings: ID, Quantity string, and Price string. It verifies that exactly two commas exist and are not adjacent. It then validates: (1) The ID length is exactly 5 and starts with 'TX'. (2) The Quantity string contains only numeric digit characters (0-9) to ensure it is a valid integer representation, converts it, and checks that it is greater than 0. (3) The Price is converted to a REAL and checked to be strictly greater than 0.0. If all criteria are met, the function returns TRUE, otherwise FALSE.

評分準則

Total Marks: 9.37
- 1.37 marks: Correct function header with parameter and return type, and appropriate declarations.
- 2.0 marks: Loop and logic to correctly find both comma positions to delimit fields.
- 2.0 marks: Proper extraction of substrings (ID, QtyStr, PriceStr) using correct start indices and lengths.
- 2.0 marks: Thorough validation of ID (length 5 and prefix 'TX') and checking that QtyStr consists entirely of digit characters.
- 2.0 marks: Correct conversion and boundary checking (> 0 for quantity, > 0.0 for price) and returning correct boolean values.
題目 2 · Pseudocode Design & Structured Analysis
9.37
An application manages player scores using two parallel 1D arrays:
- PlayerNames of type ARRAY[1:50] OF STRING
- Scores of type ARRAY[1:50] OF INTEGER

Write a pseudocode procedure SortScores(BYREF PlayerNames : ARRAY, BYREF Scores : ARRAY, Size : INTEGER) that sorts the scores in descending order using a bubble sort algorithm. Ensure that the association between player names and scores is correctly maintained during sorting.
Size represents the actual number of active elements in the arrays (where 1 <= Size <= 50).
查看答案詳解

解題

The procedure implements a standard bubble sort algorithm modified for descending order. It iterates through the array of scores, comparing adjacent elements. If a lower score precedes a higher score, they are swapped. Crucially, whenever a swap is made in the Scores array, the corresponding elements in the parallel PlayerNames array are also swapped at the same indices to maintain relationship integrity. An optimization flag, Swapped, is used to terminate early if a pass completes without any swaps.

評分準則

Total Marks: 9.37
- 1.37 marks: Correct procedure header using BYREF parameters for arrays and correct data types.
- 2.0 marks: Implementing nested loop structures representing the bubble sort logic correctly.
- 2.0 marks: Correct comparison condition (<) for descending sort order.
- 2.0 marks: Swapping elements in the Scores array using a temporary variable.
- 2.0 marks: Parallel swapping of elements in PlayerNames at identical index locations.
題目 3 · Pseudocode Design & Structured Analysis
9.37
A circular queue is implemented using a 1D array QueueData[1:100] of type STRING. The queue is managed by three global variables:
- HeadPointer (INTEGER): stores the index of the element at the front of the queue.
- TailPointer (INTEGER): stores the index of the element at the rear of the queue.
- NumItems (INTEGER): stores the current number of items in the queue.

Initially, HeadPointer is set to 1, TailPointer is set to 0, and NumItems is set to 0.

Write a pseudocode function Enqueue(NewItem : STRING) RETURNS BOOLEAN to add an item to the queue. The function must:
1. Check if the queue is full. If full, return FALSE.
2. Update the TailPointer appropriately to wrap around if it exceeds 100.
3. Insert the NewItem at the new TailPointer position.
4. Increment the NumItems counter.
5. Return TRUE to indicate successful insertion.
查看答案詳解

解題

First, the function checks if the queue is full by comparing NumItems to the maximum capacity of 100. If it is full, it immediately returns FALSE to prevent overflow. Otherwise, TailPointer is incremented by 1. Since this is a circular queue, if TailPointer exceeds 100, it wraps around back to 1. The NewItem is stored at the location specified by the updated TailPointer, NumItems is incremented by 1, and the function returns TRUE to indicate success.

評分準則

Total Marks: 9.37
- 1.37 marks: Correct function header with parameter and return type.
- 2.0 marks: Properly checking if the queue is full using NumItems and returning FALSE.
- 2.0 marks: Correctly incrementing TailPointer and wrapping it back to 1 when it exceeds 100.
- 2.0 marks: Storing NewItem at the correct index (TailPointer) in QueueData.
- 2.0 marks: Correctly incrementing NumItems and returning TRUE at the end of the operation.
題目 4 · Pseudocode Design & Structured Analysis
9.37
Write a pseudocode function ExtractDomain(Email : STRING) RETURNS STRING that takes an email address string as input. The function must extract and return the domain name (the part after the '@' symbol).

The email address is considered invalid if:
- It does not contain exactly one '@' character.
- The '@' character is at the very beginning or the very end of the string.
- It contains any space characters.

If the email address is invalid, the function should return the string "INVALID".

Assume the following built-in functions are available:
- LENGTH(StringVal : STRING) RETURNS INTEGER
- MID(StringVal : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING
查看答案詳解

解題

The function processes the string character by character using a loop. During the iteration, it immediately returns "INVALID" if any space character is encountered. It counts the number of occurrences of the '@' symbol and tracks its index position. After the loop, it checks if there is exactly one '@' character and that it does not appear at the first or last character positions. If valid, the MID function is utilized to extract and return the portion of the string starting from the character following '@' to the end of the string.

評分準則

Total Marks: 9.37
- 1.37 marks: Correct function signature, variable declarations with appropriate data types.
- 2.0 marks: Iteration through the entire string and tracking of '@' occurrences and location.
- 2.0 marks: Validation logic checking for space characters and returning "INVALID" immediately.
- 2.0 marks: Validation logic checking for exactly one '@' not at the edges (positions 1 or Length).
- 2.0 marks: Correct extraction of domain string using correct start position and length in the MID function.
題目 5 · Pseudocode Design & Structured Analysis
9.37
An array of structures is defined as follows:

TYPE Book
DECLARE ISBN : STRING
DECLARE Title : STRING
ENDTYPE

DECLARE Library : ARRAY[1:500] OF Book

The array Library is sorted in ascending alphabetical order of the ISBN field.

Write a recursive pseudocode function BinarySearch(SearchISBN : STRING, Low : INTEGER, High : INTEGER) RETURNS INTEGER that searches for a specific ISBN between the index boundaries Low and High.

If the ISBN is found, the function must return its array index. If the ISBN is not found within the limits, the function must return -1.
查看答案詳解

解題

This is a recursive implementation of binary search. The base case checks if Low > High, meaning the search space is exhausted and the item is not found, so it returns -1. Otherwise, the midpoint index Mid is calculated using integer division (DIV). It then compares the search value to Library[Mid].ISBN. If they match, Mid is returned. If the ISBN at Mid is greater than SearchISBN, the function calls itself recursively with the left sub-array (High updated to Mid - 1). Otherwise, it calls itself recursively with the right sub-array (Low updated to Mid + 1).

評分準則

Total Marks: 9.37
- 1.37 marks: Correct recursive function signature and proper declaration of local variable Mid.
- 2.0 marks: Base case checking if Low > High and returning -1.
- 2.0 marks: Correct calculation of Mid using integer division.
- 2.0 marks: Correct record field access (Library[Mid].ISBN) and matching check.
- 2.0 marks: Correct recursive calls with properly adjusted bounds (Mid - 1 and Mid + 1) and returning their results.
題目 6 · Pseudocode Design & Structured Analysis
9.37
A 2D grid of characters is declared as:
DECLARE Grid : ARRAY[1:10, 1:10] OF CHAR

Write a pseudocode function CountActiveNeighbors(Row : INTEGER, Col : INTEGER) RETURNS INTEGER that calculates the number of adjacent cells (horizontal, vertical, and diagonal) that contain the character '*'.

The cell itself at (Row, Col) should not be counted. Your function must ensure that it does not attempt to access elements outside the valid array bounds of 1 to 10 for both rows and columns.
查看答案詳解

解題

The function uses nested loops to iterate through rows R from Row - 1 to Row + 1 and columns C from Col - 1 to Col + 1. Inside the loops, it checks if the current indices R and C are within the legal range of 1 to 10 to avoid any index out of bounds error. It also ensures the cell being evaluated is not the center cell itself (i.e., not Row and Col). If both checks pass and Grid[R, C] contains '*', Count is incremented. Finally, the function returns the accumulated Count.

評分準則

Total Marks: 9.37
- 1.37 marks: Correct function header and declaration of variables (Count, R, C).
- 2.0 marks: Nested loops configured to run correctly from Row - 1 to Row + 1 and Col - 1 to Col + 1.
- 2.0 marks: Safe bounds check ensuring indices are strictly within 1 and 10.
- 2.0 marks: Exclusion condition preventing the center cell (Row, Col) from incrementing Count.
- 2.0 marks: Correct check for '*' in Grid[R, C] and returning the correct count.
題目 7 · Pseudocode Design & Structured Analysis
9.37
A system requires a validation routine to verify if a string represents a valid hexadecimal literal. The rules for validity are:
1. The string must have a minimum length of 3.
2. The string must start with the exact characters "0x" or "0X".
3. Every character following "0x" or "0X" must be a valid hexadecimal digit (i.e., '0' to '9', 'A' to 'F', or 'a' to 'f').

Write a pseudocode function IsValidHex(HexStr : STRING) RETURNS BOOLEAN to implement this validation algorithm.

Assume the following built-in functions are available:
- LENGTH(StringVal : STRING) RETURNS INTEGER
- MID(StringVal : STRING, Start : INTEGER, Length : INTEGER) RETURNS STRING
查看答案詳解

解題

The function first validates that the input string Length is at least 3. It then extracts the first two characters using MID and ensures that they match either '0x' or '0X'. Afterwards, a loop starts from index 3 up to Length, examining each character individually. If a character falls outside the acceptable range of hexadecimal digit representations ('0'-'9', 'A'-'F', or 'a'-'f'), the function returns FALSE immediately. If all characters are verified, the function returns TRUE.

評分準則

Total Marks: 9.37
- 1.37 marks: Correct function header with parameter and return types.
- 2.0 marks: Validation of string length to ensure it is at least 3 characters.
- 2.0 marks: Extracting and correctly checking the prefix for '0x' or '0X'.
- 2.0 marks: Loop starting at 3 up to string length to evaluate remaining characters.
- 2.0 marks: Range checking logic for each character (0-9, A-F, a-f) and returning appropriate booleans.
題目 8 · Pseudocode Design & Structured Analysis
9.37
A text file named Sales.txt contains numeric values representing daily sales, with each line containing one real value (e.g., 450.50).

Write a pseudocode procedure GenerateSalesReport(Threshold : REAL) that reads all numbers from Sales.txt and performs the following tasks:
1. Calculates the total of all sales.
2. Calculates the number of sales transactions that are strictly greater than Threshold.
3. Calculates the average value of those sales transactions that are strictly greater than Threshold.
4. Outputs the final results to a new text file named Report.txt in the following format:
- Line 1: Total Sales:
- Line 2: Count Above Threshold:
- Line 3: Average Above Threshold: (If no sales are above the threshold, write Average Above Threshold: 0.0)

Assume the following built-in file operations and functions are available:
- OPENFILE FOR READ / WRITE
- READFILE ,
- WRITEFILE ,
- CLOSEFILE
- EOF()
- STRING_TO_REAL(StringVal : STRING) RETURNS REAL
- NUM_TO_STRING(NumVal : REAL) RETURNS STRING
查看答案詳解

解題

The procedure starts by initializing accumulators and counters. It opens the text file Sales.txt in read mode and processes it line-by-line using a WHILE loop until the end of the file is reached. Each line is converted to a real number, added to the TotalSales accumulator, and checked against the Threshold parameter. If the sale is greater than the Threshold, the counter AboveCount is incremented and the value is added to AboveTotal. After reading the file, the file is closed. The average calculation is performed while safeguarding against division by zero (checking if AboveCount > 0). Finally, a new file Report.txt is opened for writing, and the calculated results are formatted as strings and written to the file before closing it.

評分準則

Total Marks: 9.37
- 1.37 marks: Correct procedure header and initialization of all tracking/accumulator variables.
- 2.0 marks: Opening, reading from, and closing the 'Sales.txt' file correctly with a standard EOF loop.
- 2.0 marks: Converting read string value to real and updating the running total and conditional count/sum.
- 2.0 marks: Guarding against division by zero when calculating the average above the threshold.
- 2.0 marks: Correctly opening 'Report.txt' for writing, formatting output lines with correct labels, and closing the file.

Paper 3 (Advanced Theory)

Answer all questions. Show working for calculations where required.
11 題目 · 74.91000000000001
題目 1 · Theoretical and Algorithmic Analysis
6.81
Convert the real number -6.25 into a normalised floating-point binary representation using a 12-bit format (8-bit mantissa, 4-bit exponent, both in two's complement). Show each step of your conversion process clearly.
查看答案詳解

解題

1. Express the positive real number in binary: 6.25 is 110.01 in binary. 2. To represent -6.25 in two's complement fixed-point, we can extend 6.25 (e.g., 0110.0100) and find the two's complement, which is 1001.1100. 3. To normalise a negative number, the first two bits must be 1.0. This requires shifting the binary point three places to the left: 1.0011100 * 2^3. 4. The mantissa is 10011100 (8 bits). 5. The exponent is positive 3, which is 0011 in 4-bit two's complement binary. Thus, the final representation is Mantissa: 10011100, Exponent: 0011.

評分準則

1 mark: Correct binary conversion of the magnitude 6.25. 2 marks: Correct conversion to a two's complement negative representation. 1 mark: Correct identification of the shift required (3 places to the left). 1 mark: Correct 8-bit normalised mantissa (10011100). 1 mark: Correct 4-bit exponent (0011). 0.81 marks: Structured and clear mathematical explanation of each step.
題目 2 · Theoretical and Algorithmic Analysis
6.81
In a five-stage processor pipeline consisting of Fetch (F), Decode (D), Execute (E), Memory Access (M), and Write-back (W), a data hazard can occur. Define what is meant by a data hazard, explain why it occurs in the code sequence: ADD R1, R2, R3 (writes to R1) followed immediately by SUB R4, R1, R5 (reads from R1), and describe how the processor can resolve this hazard.
查看答案詳解

解題

A data hazard is a pipeline conflict where an instruction needs data before a preceding instruction has updated it. Here, ADD writes its result to R1 in the W stage (clock cycle 5), but SUB attempts to read R1 in the D stage (clock cycle 3). This causes a read-after-write hazard. It is resolved by forwarding (bypassing the register file to feed the execution unit directly) or stalling (inserting bubbles to delay SUB until ADD completes W).

評分準則

2 marks: Clear and precise definition of a data hazard. 2 marks: Explanation of the specific conflict in the sequence (ADD updating R1 in W, SUB reading R1 in D/E). 2 marks: Clear description of at least one valid resolution method (e.g., forwarding/bypassing or stalling/bubbles). 0.81 marks: Overall technical accuracy and correct terminology.
題目 3 · Theoretical and Algorithmic Analysis
6.81
Lexical analysis is the first stage of the compilation process. Describe three essential tasks performed by a compiler during the lexical analysis stage, and explain how a transition graph is used during this stage to recognize valid identifiers.
查看答案詳解

解題

During lexical analysis, the compiler: 1. Removes unnecessary characters like whitespace, tabs, and comments. 2. Builds a symbol table containing identified keywords, constants, and variables. 3. Breaks down the source code characters into grouped lexemes and generates corresponding tokens. A transition graph represents a finite state automaton where the compiler moves from a start state, following transitions mapped to character inputs. For an identifier, the first letter triggers a transition to an accepting state, and subsequent letters or digits loop back into that accepting state. Any invalid character redirects to an error handling state.

評分準則

3 marks: Three correct and distinct tasks of lexical analysis. 3 marks: Detailed explanation of transition graph application (start state, input-driven state changes, loops, and accepting states). 0.81 marks: Quality and clarity of technical communication.
題目 4 · Theoretical and Algorithmic Analysis
6.81
Explain the sequence of steps a web browser performs to verify that a digital certificate presented by a secure website (using HTTPS) is valid, authentic, and safe to trust.
查看答案詳解

解題

1. The browser extracts the digital signature from the certificate and identifies the Certificate Authority (CA) that issued it. 2. The browser looks up the CA's public key from its pre-installed, trusted root store. 3. The browser uses the CA's public key to decrypt the digital signature, revealing the original hash calculated by the CA. 4. The browser independently hashes the certificate's main content using the specified cryptographic hash function. 5. The browser compares the decrypted hash with its recalculated hash; a match proves the content has not been altered. 6. The browser checks the certificate's validity dates (expiration) and queries the CA's revocation list (via CRL or OCSP) to ensure it hasn't been revoked. 7. The browser verifies that the domain name on the certificate matches the domain name of the accessed website.

評分準則

2 marks: Identifying the use of CA's public key to decrypt the signature. 2 marks: Detailing the comparison of the decrypted hash with the browser's recalculated hash. 2 marks: Describing additional validation checks (expiration dates, revocation status, domain match). 0.81 marks: Consistent step-by-step logic.
題目 5 · Theoretical and Algorithmic Analysis
6.81
Deep learning networks depend on complex training regimes. Explain the purpose of a loss function in an Artificial Neural Network (ANN) and describe the sequential steps involved in backpropagation to update the network's parameters.
查看答案詳解

解題

The loss function quantifies the mathematical difference (error) between the actual output vector produced by the neural network and the desired target vector. During backpropagation, this calculated error is propagated backwards through the network layer by layer. The partial derivatives (gradients) of the loss function with respect to every weight and bias are computed using the calculus chain rule. These gradients determine how a change in each parameter affects the overall loss. Finally, an optimization algorithm (such as gradient descent) uses these gradients, multiplied by a configured learning rate, to adjust the weights and biases in the direction that minimizes the loss.

評分準則

2 marks: Clear definition and purpose of the loss function. 3 marks: Detailed step-by-step process of backpropagation (backward error propagation, calculation of gradients using the chain rule). 1.81 marks: Explanation of weight/bias adjustment via gradient descent and learning rate.
題目 6 · Theoretical and Algorithmic Analysis
6.81
A state machine for a smart vending machine operates on three states: Idle, Selecting, and Dispensing. The machine transitions as follows: 1. From Idle, a 'coin_inserted' input moves it to Selecting. 2. From Selecting, a 'cancel_pressed' input returns the coin and moves it back to Idle. 3. From Selecting, an 'item_selected' input moves it to Dispensing. 4. From Dispensing, an 'item_dropped' input moves it back to Idle. Construct a state transition table representing this machine with columns: Current State, Input Trigger, Next State, and Output Action.
查看答案詳解

解題

The state transition table contains: Row 1: Current State: Idle | Input: coin_inserted | Next State: Selecting | Output Action: Display 'Select Item'. Row 2: Current State: Selecting | Input: cancel_pressed | Next State: Idle | Output Action: Return Coin. Row 3: Current State: Selecting | Input: item_selected | Next State: Dispensing | Output Action: Drop Item. Row 4: Current State: Dispensing | Input: item_dropped | Next State: Idle | Output Action: Display 'Thank You' (or clear selection).

評分準則

1.5 marks: For each of the four fully completed and logically correct transition rows (each requiring Current State, Input, Next State, and associated Output Action). 0.81 marks: Correct tabular structure and comprehensive logical consistency.
題目 7 · Theoretical and Algorithmic Analysis
6.81
Describe how a router processes and forwards packets of data across a network, and explain the key differences between static and dynamic routing tables.
查看答案詳解

解題

When an incoming IP packet arrives at a router's port, the router extracts the destination IP address from the packet header. It performs a lookup in its internal routing table to match the destination subnet with the most specific path (longest prefix match). The router updates packet header fields (such as decrementing the TTL to prevent infinite loops) and encapsulates the packet into a new link-layer frame, forwarding it out the identified interface. A static routing table is populated manually by an administrator; it does not adapt automatically to link failures. In contrast, a dynamic routing table uses active routing protocols (such as OSPF, RIP, or BGP) to communicate with adjacent routers and automatically recalculate optimal paths when topology changes occur.

評分準則

3 marks: Explanation of router packet processing (IP extraction, lookup, header/TTL update, encapsulation, and interface forwarding). 3 marks: Contrast between static (manual entry, rigid) and dynamic routing (protocol-driven, automatic updates, resilient). 0.81 marks: Structured language and accurate terminology usage.
題目 8 · Theoretical and Algorithmic Analysis
6.81
In Object-Oriented Programming (OOP), explain the concepts of Inheritance and Polymorphism. For each concept, provide a practical software design example that illustrates its benefit to code maintainability.
查看答案詳解

解題

Inheritance is a mechanism where a child class (subclass) inherits attributes and methods from a parent class (superclass), promoting code reuse and establishing an 'is-a' relationship. Example: A parent class 'Employee' holds fields 'name' and 'salary', and child classes 'Manager' and 'Engineer' inherit these fields without redefining them. Polymorphism allows a single method interface to behave differently depending on the concrete object calling it, typically implemented via method overriding. Example: An abstract class 'Shape' defines a 'draw()' method. Subclasses 'Circle' and 'Square' override 'draw()' to render different graphics. A rendering loop can call 'draw()' on any shape object dynamically without knowing its exact concrete class type at compile time.

評分準則

3 marks: Complete explanation and valid example of Inheritance. 3 marks: Complete explanation and valid example of Polymorphism. 0.81 marks: Discussion of how these principles directly improve software maintainability (e.g., code reuse and decoupling).
題目 9 · Theoretical and Algorithmic Analysis
6.81
A real binary value is stored in floating-point format using 12 bits: 8 bits for the mantissa and 4 bits for the exponent, both in two's complement. (a) Convert the 12-bit floating-point number represented in binary below into denary. Show your working. Mantissa: 10011010, Exponent: 0101. (b) Explain how a computer system can determine that this particular negative floating-point number is stored in a normalised format.
查看答案詳解

解題

Part (a): 1. Determine the value of the exponent: The exponent is 0101 in two's complement. Since the most significant bit is 0, it is a positive number. \( 0101_2 = 1 \times 2^2 + 1 \times 2^0 = 5 \). So, the exponent is \( +5 \). 2. Determine the value of the mantissa: The mantissa is 10011010 in two's complement, with the binary point after the first bit (sign bit): \( 1.0011010 \). Since the first bit is 1, it is a negative number. We can convert it by taking the two's complement: Invert the bits: 01100101, Add 1: 01100110. In denary, this is: \( 0.5 + 0.25 + 0.03125 + 0.015625 = 0.796875 \). So the original mantissa value is \( -0.796875 \). Alternatively, using direct weights: \( -1 \times 2^0 + 0 \times 2^{-1} + 0 \times 2^{-2} + 1 \times 2^{-3} + 1 \times 2^{-4} + 0 \times 2^{-5} + 1 \times 2^{-6} + 0 \times 2^{-7} = -1 + 0.125 + 0.0625 + 0.015625 = -0.796875 \). 3. Calculate the final value: \( \text{Mantissa} \times 2^{\text{exponent}} = -0.796875 \times 2^5 = -0.796875 \times 32 = -25.5 \). Part (b): 1. For a floating-point number to be normalised, it must use the maximum possible precision. 2. In two's complement, this means the sign bit (the first bit) and the first fractional bit (the second bit) must be different. 3. For negative numbers, the sign bit is 1, so the next bit must be 0 (i.e., it must start with 10). 4. The mantissa is 10011010, which starts with 10, confirming that it is normalised.

評分準則

Part (a) [4 marks]: - 1 mark: Correctly converting exponent 0101 to denary 5. - 1 mark: Correctly showing the calculation for a negative mantissa (either by two's complement inversion or using direct place weights). - 1 mark: Correct denary value of mantissa: -0.796875 (or -102/128). - 1 mark: Correct final denary value of -25.5. Part (b) [2.81 marks]: - 1 mark: Stating that normalisation requires the first two bits of the mantissa to be different. - 1 mark: Specifying that for a negative number, the first two bits must start with 10. - 0.81 marks: Explicitly linking this to the given mantissa starting with 10.
題目 10 · Theoretical and Algorithmic Analysis
6.81
A compiler developer uses the following Backus-Naur Form (BNF) rules to parse hexadecimal numbers: ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F; ::= # | 0x; ::= | . (a) Show that the string '#A5' is a valid by tracing its derivation step-by-step from the BNF rules. (b) Explain why the string '0x' is NOT a valid according to these rules. (c) Rewrite the BNF rules so that a can optionally end with an uppercase 'H' character (e.g. '#A5H' and '0x3FH' are valid, while '#A5' is still valid).
查看答案詳解

解題

Part (a): Step-by-step derivation: 1. Identify that the string ends with '5'. Under the rule ::= , we match the last character '5' to . 2. This leaves '#A' as the preceding . 3. We parse '#A' using the rule ::= . 4. '#' matches . 5. 'A' matches . 6. Since all parts have been resolved to terminal symbols, '#A5' is a valid . Part (b): 1. The base rule to create a is ::= . 2. This requires at least one to follow the . 3. The string '0x' matches but contains no subsequent characters, so it cannot be matched to . Thus, it is invalid. Part (c): To make 'H' optional at the end, we can split the definition into a body (which has the digits) and the optional suffix. New rules: ::= | and ::= | H (while retaining the original definitions of and ).

評分準則

Part (a) [3 marks]: - 1 mark: Identifies the recursive rule ::= split where '5' is the . - 1 mark: Identifies that '#A' is resolved to . - 1 mark: Correctly maps '#' to and 'A' to to complete the derivation. Part (b) [1.81 marks]: - 1 mark: Explains that requires a prefix followed by at least one . - 0.81 marks: Explicitly states that '0x' only matches and has no trailing digit, failing the syntax. Part (c) [2 marks]: - 1 mark: Introduces a new intermediate rule/structure (such as ) that handles the prefix and digits recursively. - 1 mark: Defines to resolve to either this intermediate structure on its own, or with 'H' appended.
題目 11 · Theoretical and Algorithmic Analysis
6.81
A binary tree is implemented using a global 1D array of records named Tree. The index of the root node is stored in a global variable RootPointer. The records are defined as follows: TYPE Node DECLARE Value : INTEGER DECLARE LeftChild : INTEGER DECLARE RightChild : INTEGER ENDTYPE. A value of -1 in LeftChild or RightChild indicates that no child node exists. Write a recursive pseudocode function SumEvenValues(NodePointer : INTEGER) RETURNS INTEGER that traverses the binary tree and returns the sum of all the Value fields that are even numbers. If the tree is empty, the pointer passed is -1, in which case the function should return 0.
查看答案詳解

解題

The recursive algorithm must perform a traversal of the binary tree. 1. Base Case: If the passed pointer (NodePointer) is -1, it represents an empty child subtree. The function must return 0 immediately to stop the recursion. 2. Check for Even Value: If NodePointer is valid (not -1), we access the node value: Tree[NodePointer].Value. We determine if this value is even by checking if Value MOD 2 = 0. If it is even, we set a temporary sum variable to this value. Otherwise, we set it to 0. 3. Recursive Step: The function then calls itself recursively twice: once for the left subtree (Tree[NodePointer].LeftChild) and once for the right subtree (Tree[NodePointer].RightChild). The returned value is the sum of the current node's value (if even) plus the results of both recursive calls. 4. Structure: Use standard Cambridge pseudocode syntax with FUNCTION, RETURNS, IF, THEN, ELSE, ENDIF, RETURN, and ENDFUNCTION declarations.

評分準則

Recursive function implementation [6.81 marks total]: - 1 mark: Correct function header with parameter NodePointer : INTEGER and return type RETURNS INTEGER. - 1 mark: Base case checking if NodePointer = -1 and returning 0. - 1 mark: Extracting the value Tree[NodePointer].Value. - 1 mark: Checking if the value is even using MOD 2 = 0 (or division equivalent). - 1 mark: Making correct recursive call to SumEvenValues with Tree[NodePointer].LeftChild as argument. - 1 mark: Making correct recursive call to SumEvenValues with Tree[NodePointer].RightChild as argument. - 0.81 marks: Adding the current even value (or 0 if odd) to the results of both recursive calls, returning the correct combined sum, and correctly closing with ENDFUNCTION.

Paper 4 (Practical)

Write functional code in Python, Java, or Visual Basic. Save code files and submit screenshots of execution.
3 題目 · 75
題目 1 · Hands-on Programming Tasks
25
An IT department manages service tickets using a priority-ordered linked list. Each ticket has a unique ID, priority level (1 to 10, where 10 is the highest), and description.

1. Create a class `TicketNode` with private fields: `TicketID` (string), `Priority` (integer), `Description` (string), and `NextNode` (integer, pointer to the next node). Provide a constructor that initializes these fields to values passed as parameters, and write public getter and setter methods for all fields. [8 marks]

2. In your main program, declare a 1D array of 5 elements of type `TicketNode`. Initialize this array to form a free list, where each node points to the next available position, and the last node points to -1. Initialize `StartPointer` to -1 and `FreePointer` to 0. Write a procedure `InitializeList()` to achieve this. [5 marks]

3. Write a function `InsertTicket(TicketID, Priority, Description)` that inserts a new ticket into the linked list such that the list remains sorted in descending order of priority (highest priority ticket at the start). If the list is full, display an appropriate message. Update pointers accordingly. [9 marks]

4. Write a procedure `PrintActiveTickets()` that outputs the ID, priority, and description of all currently active tickets in priority order. [3 marks]
查看答案詳解

解題

The program defines a node structure that holds ticket information and pointers using OOP paradigm. It implements the standard linked list insertion algorithm with logic for priority ordering.

### Python Implementation:
```python
class TicketNode:
def __init__(self, ticket_id, priority, description, next_node):
self.__TicketID = ticket_id
self.__Priority = priority
self.__Description = description
self.__NextNode = next_node

def get_ticket_id(self): return self.__TicketID
def get_priority(self): return self.__Priority
def get_description(self): return self.__Description
def get_next_node(self): return self.__NextNode

def set_ticket_id(self, val): self.__TicketID = val
def set_priority(self, val): self.__Priority = val
def set_description(self, val): self.__Description = val
def set_next_node(self, val): self.__NextNode = val

List = [None] * 5
StartPointer = -1
FreePointer = 0

def InitializeList():
global List, StartPointer, FreePointer
for i in range(4):
List[i] = TicketNode("", 0, "", i + 1)
List[4] = TicketNode("", 0, "", -1)
StartPointer = -1
FreePointer = 0

def InsertTicket(ticket_id, priority, description):
global StartPointer, FreePointer, List
if FreePointer == -1:
print("List is full")
return False

new_node_index = FreePointer
FreePointer = List[FreePointer].get_next_node()

List[new_node_index].set_ticket_id(ticket_id)
List[new_node_index].set_priority(priority)
List[new_node_index].set_description(description)
List[new_node_index].set_next_node(-1)

current = StartPointer
previous = -1

while current != -1 and List[current].get_priority() >= priority:
previous = current
current = List[current].get_next_node()

if previous == -1:
List[new_node_index].set_next_node(StartPointer)
StartPointer = new_node_index
else:
List[new_node_index].set_next_node(current)
List[previous].set_next_node(new_node_index)
return True

def PrintActiveTickets():
global StartPointer, List
current = StartPointer
if current == -1:
print("No active tickets.")
return
while current != -1:
print(f"ID: {List[current].get_ticket_id()}, Priority: {List[current].get_priority()}, Desc: {List[current].get_description()}")
current = List[current].get_next_node()
```

評分準則

- Class definition with private attributes and parameterised constructor [4 marks]
- Correct implementation of all getter and setter methods [4 marks]
- InitializeList correct configuration of array and free pointers [5 marks]
- InsertTicket array full checks [1 mark]
- Fetching correct index and updating FreePointer [2 marks]
- Traversal loop stopping at correct place for sorted descending placement [3 marks]
- Insertion pointer manipulation logic (start of list vs. middle/end) [3 marks]
- PrintActiveTickets traversal of linked list and printing details [3 marks]
題目 2 · Hands-on Programming Tasks
25
A program is required to manage scores for an arcade game. The scores are stored in a text file named `scores.txt` with one score (integer) per line.

1. Write Python code to create the text file `scores.txt` containing 10 integer scores (e.g., 150, 80, 240, 310, 95, 420, 110, 205, 180, 300). [2 marks]

2. Write a procedure `LoadScores()` that reads the values from `scores.txt` and stores them into a global 1D array of 10 integers named `ScoreArray`. [5 marks]

3. Write a recursive function `RecursiveSearch(Target, Low, High)` that searches for a specific score in `ScoreArray` using binary search. The array must be sorted first. The function must return the index of the score if found, or -1 if not found. [10 marks]

4. Write a recursive function `SumAboveThreshold(Index, Threshold)` that calculates and returns the sum of all scores in `ScoreArray` starting from the given `Index` to the end of the array, but only including scores that are strictly greater than `Threshold`. [5 marks]

5. Write code in the main program to test all of these functions: load the scores, sort them, search for the score `205`, and calculate the sum of scores above `150`. Output the results clearly. [3 marks]
查看答案詳解

解題

This program covers standard A Level File handling, recursive operations (Binary Search), and recursive cumulative sum calculation.

### Python Implementation:
```python
# Write scores.txt
with open("scores.txt", "w") as f:
for s in [150, 80, 240, 310, 95, 420, 110, 205, 180, 300]:
f.write(f"{s}
")

ScoreArray = [0] * 10

def LoadScores():
global ScoreArray
try:
with open("scores.txt", "r") as f:
for i in range(10):
line = f.readline().strip()
if line:
ScoreArray[i] = int(line)
except FileNotFoundError:
print("File not found.")

def RecursiveSearch(Target, Low, High):
global ScoreArray
if Low > High:
return -1
mid = (Low + High) // 2
if ScoreArray[mid] == Target:
return mid
elif ScoreArray[mid] > Target:
return RecursiveSearch(Target, Low, mid - 1)
else:
return RecursiveSearch(Target, mid + 1, High)

def SumAboveThreshold(Index, Threshold):
global ScoreArray
if Index >= len(ScoreArray):
return 0
current_val = ScoreArray[Index]
added_value = current_val if current_val > Threshold else 0
return added_value + SumAboveThreshold(Index + 1, Threshold)
```

評分準則

- File writing correct containing 10 integer values [2 marks]
- LoadScores successfully opens scores.txt, reads values line-by-line [3 marks]
- Correct cast to integer and saving in 1D array, handling error [2 marks]
- RecursiveSearch base case `Low > High` returning -1 [2 marks]
- Midpoint calculations and comparison correctness [3 marks]
- Correct recursive call sequences with altered pointers (`mid - 1`, `mid + 1`) [5 marks]
- SumAboveThreshold base case check correctly implemented [2 marks]
- Correct accumulator addition and recursive call delegation [3 marks]
- Main code sorting array, searching target, calling sum, output verification [3 marks]
題目 3 · Hands-on Programming Tasks
25
A car rental agency requires an object-oriented program to manage bookings.

1. Create a base class `Vehicle` with:
- Private attributes: `__Registration` (string), `__BaseFee` (real), `__DailyRate` (real).
- A constructor that initializes these three attributes with values passed as parameters.
- Getter methods for all three attributes.
- A method `CalculateRentalCost(Days)` which returns a real value representing the rental cost calculated as: `BaseFee + (DailyRate * Days)`. [8 marks]

2. Create a subclass `ElectricVehicle` that inherits from `Vehicle`. It must include:
- Private attributes: `__BatteryCapacity` (integer) and `__DiscountRate` (real, e.g., 0.10 for 10% discount).
- A constructor that accepts arguments for registration, base fee, daily rate, battery capacity, and discount rate, and calls the parent class constructor correctly.
- Getter methods for battery capacity and discount rate.
- Overridden method `CalculateRentalCost(Days)` that calculates the standard rental cost using the parent method, applies the discount rate to it (e.g., standard cost * (1 - discount rate)), and returns the discounted total. [7 marks]

3. Write main program code to:
- Declare a 1D array of size 3 of type `Vehicle`.
- Instantiate two standard `Vehicle` objects and one `ElectricVehicle` object into this array with realistic sample values.
- Write a procedure `DisplayRentalCosts(VehicleArray, Days)` that iterates through the array and outputs each vehicle's registration and its total rental cost for the given number of days. [10 marks]
查看答案詳解

解題

This is a classic OOP scenario demonstrating constructor inheritance and method overriding (polymorphism).

### Python Implementation:
```python
class Vehicle:
def __init__(self, registration, base_fee, daily_rate):
self.__Registration = registration
self.__BaseFee = float(base_fee)
self.__DailyRate = float(daily_rate)

def GetRegistration(self): return self.__Registration
def GetBaseFee(self): return self.__BaseFee
def GetDailyRate(self): return self.__DailyRate

def CalculateRentalCost(self, Days):
return self.__BaseFee + (self.__DailyRate * Days)

class ElectricVehicle(Vehicle):
def __init__(self, registration, base_fee, daily_rate, battery_capacity, discount_rate):
super().__init__(registration, base_fee, daily_rate)
self.__BatteryCapacity = int(battery_capacity)
self.__DiscountRate = float(discount_rate)

def GetBatteryCapacity(self): return self.__BatteryCapacity
def GetDiscountRate(self): return self.__DiscountRate

def CalculateRentalCost(self, Days):
standard_cost = super().CalculateRentalCost(Days)
return standard_cost * (1 - self.__DiscountRate)
```

評分準則

- Base class Vehicle with private fields and parameterized constructor [4 marks]
- Getters implemented correctly in Vehicle [2 marks]
- Vehicle CalculateRentalCost calculation logic correct [2 marks]
- Subclass ElectricVehicle syntax, inheriting correctly from Vehicle [2 marks]
- ElectricVehicle constructor properly calling the parent constructor (`super()`) [2 marks]
- Overridden CalculateRentalCost utilizing parent class logic and applying discount [3 marks]
- Declaring and instantiating 1D array of 3 Vehicle objects with accurate parameters [3 marks]
- DisplayRentalCosts loop checking for null and outputting correctly formatted cost [4 marks]
- Evidence of program output verification [3 marks]

想知道自己有幾分把握?

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

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

免費開始練習