An original Thinka practice paper modelled on the structure and difficulty of the Jun 2024 (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.
20 題目 · 76 分
題目 1 · Short Answer
3 分
A computer system represents signed integers in an 8-bit register using two's complement. Explain the steps to represent the decimal value -87 in this register, showing the final binary representation.
查看答案詳解收起答案詳解
解題
Step 1: Convert the positive value 87 to an 8-bit binary number. 87 = 64 + 16 + 4 + 2 + 1, which gives 01010111. Step 2: Perform the one's complement by inverting all the bits, which changes 01010111 to 10101000. Step 3: Add 1 to the least significant bit of the inverted value to complete the two's complement, giving 10101001.
評分準則
1 mark: Correct binary representation of positive 87 (01010111). 1 mark: Correctly inverting all bits (10101000). 1 mark: Correctly adding 1 to yield the final correct answer (10101001).
題目 2 · Short Answer
3 分
Referential integrity is a fundamental principle in relational databases. Define referential integrity and explain how a database management system (DBMS) uses foreign keys to maintain it.
查看答案詳解收起答案詳解
解題
Referential integrity ensures that the relationships between tables in a database remain accurate and consistent. This is implemented via foreign keys, where a foreign key field in one table links to the primary key in another table. The database system monitors actions and prevents operations that violate this relationship, ensuring no orphaned records are created.
評分準則
1 mark: Definition of referential integrity (maintaining consistency/validity of relationships between tables). 1 mark: Explanation of the foreign key to primary key linkage. 1 mark: Explanation of how DBMS prevents integrity violations (e.g., blocking deletions of referenced records or blocking invalid inserts).
題目 3 · Short Answer
3 分
A laser printer is commonly used in offices for high-speed printing. Describe how a laser printer prints a page of text, focusing on the roles of the drum, laser, and toner.
查看答案詳解收起答案詳解
解題
The printing process starts with a drum receiving a uniform static charge. A laser beam then scans the drum, discharging specific points to write a latent electrostatic image. Oppositely charged toner is attracted to these discharged spots. Finally, the toner is transferred to the paper and fused into place using heated rollers.
評分準則
1 mark: Mention of the drum receiving a static charge. 1 mark: Laser beam selectively discharging areas of the drum to create the image outline. 1 mark: Toner being attracted to the drum and transferred to the paper, then fused using heat and pressure.
題目 4 · Short Answer
3 分
A web application requires users to enter their credentials to log in. Explain three reasons why a developer must use server-side scripting rather than client-side scripting to process this login validation.
查看答案詳解收起答案詳解
解題
Client-side scripting executes code on the user's browser, meaning login validation code and database queries would be exposed to potential attackers. By using server-side scripting, the verification is done entirely on the secure host server. This protects sensitive database credentials, prevents the user from bypassing validation checks, and guarantees execution regardless of client configuration.
評分準則
1 mark: Security of code and database credentials (not visible to user). 1 mark: Secure access to the central server's database. 1 mark: Independence from client-side settings / browser configurations (e.g., disabled scripting).
題目 5 · Short Answer
3 分
In assembly language, the comparison instruction CMP is often followed by a conditional jump instruction. Explain the role of the Status Register (SR) in this process.
查看答案詳解收起答案詳解
解題
The Status Register holds system flags that change based on ALU results. The CMP instruction performs a subtraction between two operands. Instead of storing the numeric result, it updates flags like Zero (Z), Negative (N), and Overflow (V) in the Status Register. The next conditional jump instruction checks these flags to determine if the jump criteria are satisfied.
評分準則
1 mark: Identifying that the Status Register contains status flags (e.g., Z, N, C, V) representing the state of the last operation. 1 mark: Explaining that CMP performs a comparison/subtraction and updates these flags without changing operand values. 1 mark: Explaining that conditional jump instructions inspect these flags to make branching decisions.
題目 6 · Short Answer
3 分
Disk defragmentation is a common system utility task. Explain how disk defragmentation software works and how it improves the read and write performance of a magnetic hard disk.
查看答案詳解收起答案詳解
解題
Over time, files stored on a magnetic hard disk become fragmented, with parts of a single file spread across different tracks and sectors. Defragmentation utility software identifies these scattered parts and physically relocates them so that each file is stored in contiguous sectors. This significantly reduces the physical travel time of the read/write drive head, boosting system speed.
評分準則
1 mark: Stating that it reorganizes file segments scattered across the disk. 1 mark: Explaining that it rearranges segments so that files are stored in contiguous sectors/blocks. 1 mark: Connecting this contiguous storage to reduced physical read/write head movement, resulting in faster data access.
題目 7 · Short Answer
3 分
A sender wants to send a secure email to a recipient and needs to guarantee that the message has not been altered during transmission. Describe how a digital signature is created and attached to the email to ensure authenticity.
查看答案詳解收起答案詳解
解題
The process of signing an email involves: 1) The sender uses a hash function to compute a unique hash value (digest) of the message content. 2) The sender encrypts this hash value with their own private key, which becomes the digital signature. 3) The digital signature is sent alongside the email. The recipient can decrypt this signature with the sender's public key to verify that the message has not been tampered with.
評分準則
1 mark: The message content is passed through a hashing algorithm to create a unique hash digest. 1 mark: The sender encrypts this hash digest using their private key to form the digital signature. 1 mark: The digital signature is attached to the email for transmission (which the recipient decrypts using the sender's public key to check consistency).
題目 8 · Short Answer
3 分
State three distinct differences between Shareware and Free Software (Software Libre).
查看答案詳解收起答案詳解
解題
Shareware is commercial software distributed for free on a trial basis, keeping its source code proprietary and prohibiting modifications. Free Software (Software Libre), however, respects users' freedoms, providing full access to the source code, allowing changes, modifications, and free distribution, and is typically completely free of charge.
評分準則
1 mark: Contrast regarding cost/trial (Shareware is trial-based/commercial, Free Software is completely free of charge and trial constraints). 1 mark: Contrast regarding source code access (Shareware is closed source, Free Software is open source). 1 mark: Contrast regarding modification/redistribution rights (Shareware restricts modification/sharing, Free Software encourages and legalizes it).
題目 9 · Short Answer
3 分
State three characteristics of a vector graphic that distinguish it from a bitmap image.
查看答案詳解收起答案詳解
解題
Vector graphics are based on mathematical representations (such as lines, curves, and shapes) rather than a grid of individual pixels. Because of this, they can be scaled infinitely without any loss of quality or pixelation. Additionally, they generally require less storage space for simple drawings since they only store the instructions to draw the shapes rather than color data for every single pixel.
評分準則
Award 1 mark for each valid characteristic up to a maximum of 3 marks: - Vector graphics store geometric shapes, objects, or mathematical formulas (whereas bitmaps store a grid of individual pixels) [1 mark]. - Vector graphics do not lose quality / become pixelated when scaled or resized (whereas bitmaps lose quality/pixelate) [1 mark]. - Vector graphics typically have smaller file sizes (for simple illustrations) because they only store drawing parameters (whereas bitmaps require data for every pixel) [1 mark]. - Individual components/objects in a vector graphic can be edited independently (whereas bitmaps require editing at the pixel level) [1 mark].
題目 10 · Short Answer
3 分
A relational database uses primary and foreign keys. Explain the relationship between primary and foreign keys and how they are used to link tables.
查看答案詳解收起答案詳解
解題
In a relational database, tables are linked together using keys. The primary key is a unique identifier for a record in the parent table. To establish a link, this primary key is added as a field (the foreign key) in the related (child) table. This creates a relationship (typically a 1-to-many relationship) where multiple records in the child table can refer back to a single record in the parent table, while maintaining referential integrity.
評分準則
Award marks as follows (maximum 3 marks): - State that a primary key uniquely identifies a record/row in a table [1 mark]. - State that a foreign key is a field in one table that references/links to the primary key of another table [1 mark]. - Explain that matching the foreign key value to the primary key value establishes a relationship (typically a one-to-many relationship) between the tables [1 mark]. - Explain that this link enforces referential integrity (e.g., preventing orphaned records in the child table) [1 mark].
題目 11 · Short Answer
3 分
The system bus in a computer consists of three distinct buses. Describe the function of the data bus, the address bus, and the control bus.
查看答案詳解收起答案詳解
解題
- Data Bus: A bi-directional bus that transmits the actual data or instruction codes between the CPU, memory, and input/output devices. - Address Bus: A unidirectional bus that carries the physical memory address of the location where data is to be read from or written to. - Control Bus: A bi-directional bus that transmits control signals and timing commands (such as read/write requests, clock pulses, and interrupt signals) to manage the activities of all system components.
評分準則
Award 1 mark for each correct description up to a maximum of 3 marks: - Data Bus: Transports data/instructions between the CPU and memory or I/O devices (bi-directional) [1 mark]. - Address Bus: Transports the memory address of the location currently being read from or written to (unidirectional from CPU) [1 mark]. - Control Bus: Transports control, command, and synchronization signals (such as read/write instructions and interrupt requests) to coordinate system operations [1 mark].
題目 12 · Short Answer
3 分
Describe how a checksum is used to detect errors during data transmission.
查看答案詳解收起答案詳解
解題
To detect transmission errors, the sender runs a specific algorithm on the block of data to generate a numerical checksum value. This value is appended to the data block and transmitted. Upon receiving the transmission, the receiver runs the same algorithm on the received data block. The receiver then compares its calculated checksum with the transmitted checksum. If the two values match, the data is assumed to be error-free; if they do not match, a transmission error has occurred.
評分準則
Award marks as follows (maximum 3 marks): - The sending device applies an algorithm/formula to the data block to calculate a checksum value [1 mark]. - The checksum value is transmitted along with the data [1 mark]. - The receiving device applies the same algorithm to the received data to generate its own checksum [1 mark]. - The receiver compares the calculated checksum with the transmitted checksum; a mismatch indicates a transmission error [1 mark].
題目 13 · Structured Writing
5 分
Convert the negative denary value \(-3.25\) into a 12-bit normalized floating-point binary number using two's complement, with 8 bits for the mantissa and 4 bits for the exponent. Describe each stage of your working clearly.
查看答案詳解收起答案詳解
解題
1. Convert the absolute denary number 3.25 to fixed-point binary: 3 is 11, and 0.25 is 0.01, giving 11.01. 2. Write this as an 8-bit two's complement representation: +3.25 is 0011.0100. Inverting the bits gives 1100.1011, and adding 1 gives 1100.1100. 3. Normalize the binary number. A normalized negative number must start with 1.0. Shift the binary point 2 places to the left to obtain 1.0011000. 4. Calculate the exponent. Shifting 2 places to the left means multiplying by \(2^2\), so the exponent is +2. 5. Convert the exponent +2 to a 4-bit binary value: 0010. 6. Combine the 8-bit mantissa (10011000) and 4-bit exponent (0010).
評分準則
1 mark: Identify positive binary representation is 11.01 or 0011.0100. 1 mark: Apply two's complement correctly to obtain 1100.1100. 1 mark: Shift binary point correctly to get normalized mantissa starting with 1.0 (1.0011000). 1 mark: Correct exponent value of +2. 1 mark: Correct 4-bit exponent representation (0010) and correct final mantissa/exponent combination.
題目 14 · Structured Writing
5 分
A declarative programming database contains the following Prolog facts: parent(albert, bob). parent(bob, charlie). parent(bob, diana). parent(elisa, bob). (a) Write a Prolog rule for grandparent(X, Y) where X is the grandparent of Y. (b) Explain how the Prolog interpreter uses backtracking to find all solutions to the query grandparent(albert, Who).
查看答案詳解收起答案詳解
解題
(a) Rule: grandparent(X, Y) :- parent(X, Z), parent(Z, Y). (b) 1. The query grandparent(albert, Who) unifies X with albert and Y with Who. 2. The interpreter sets subgoals parent(albert, Z) and parent(Z, Who). 3. It searches facts from top to bottom, matches parent(albert, bob) and binds Z to bob. 4. It then attempts parent(bob, Who) and finds parent(bob, charlie), returning Who = charlie as the first solution. 5. To find more solutions, it backtracks to the last choice point, attempts parent(bob, Who) again, matches parent(bob, diana), and returns Who = diana.
評分準則
2 marks: Correct Prolog rule (1 mark for correct structure/syntax, 1 mark for correct logic using an intermediate variable Z). 3 marks for backtracking explanation: 1 mark for explaining the binding of Z to bob via parent(albert, Z); 1 mark for finding the first match charlie; 1 mark for explaining backtracking to the choice point to find diana.
題目 15 · Structured Writing
5 分
A database table is defined as: STUDENT_SPORTS(StudentID, StudentName, SportCode, SportName, Fee). Each student has a unique StudentID and StudentName. A student can enroll in multiple sports. Each sport has a unique SportCode, SportName, and a fixed Fee. (a) Explain why STUDENT_SPORTS is not in Third Normal Form (3NF). (b) Design a set of normalized 3NF relations for this scenario, identifying all primary keys and foreign keys.
查看答案詳解收起答案詳解
解題
(a) The composite primary key for STUDENT_SPORTS is (StudentID, SportCode). The table has partial key dependencies, which violates Second Normal Form (and therefore Third Normal Form): StudentName depends only on StudentID, while SportName and Fee depend only on SportCode. (b) To achieve 3NF, the relation must be split: 1. STUDENT(StudentID, StudentName) [Primary Key: StudentID] 2. SPORT(SportCode, SportName, Fee) [Primary Key: SportCode] 3. REGISTRATION(StudentID, SportCode) [Primary Key: (StudentID, SportCode); Foreign Keys: StudentID references STUDENT, SportCode references SPORT].
評分準則
2 marks: Explanation of why it is not in 3NF (1 mark for identifying that (StudentID, SportCode) is the composite primary key, 1 mark for explaining that partial dependencies exist, such as StudentName depending only on StudentID). 3 marks: Normalized relations (1 mark for STUDENT table, 1 mark for SPORT table, 1 mark for REGISTRATION table with primary and foreign keys correctly identified).
題目 16 · Structured Writing
5 分
In the context of system virtualization: (a) Contrast the roles of a host operating system and a guest operating system. (b) Explain one limitation of running a performance-critical database server within a virtual machine.
查看答案詳解收起答案詳解
解題
(a) The Host Operating System is installed directly on the physical hardware. It manages physical resources and runs the hypervisor. The Guest Operating System runs inside a virtual machine managed by the hypervisor, interacting with virtualized hardware resources instead of actual physical hardware. (b) Running a database inside a virtual machine introduces performance overhead. Every input/output (I/O) operation and memory allocation must be translated by the hypervisor, leading to increased latency and decreased throughput compared to a bare-metal installation.
評分準則
2 marks: Contrast host vs guest (1 mark for describing host OS running on bare metal, 1 mark for describing guest OS running in a virtual machine). 3 marks: Explanation of a limitation (1 mark for identifying performance overhead/I/O latency, 1 mark for explaining how hypervisor translation causes this latency, 1 mark for applying this specifically to a resource-intensive system like a database).
題目 17 · Structured Writing
5 分
A binary search tree is created by inserting the following numbers in sequence: 15, 8, 24, 5, 12, 19, 30. (a) Describe the structure of the resulting binary search tree by stating the left and right child of each non-leaf node. (b) State the exact sequence of nodes visited when performing a post-order traversal on this tree.
查看答案詳解收起答案詳解
解題
(a) Structure: Root node is 15. Root 15 has left child 8 and right child 24. Node 8 has left child 5 and right child 12. Node 24 has left child 19 and right child 30. Nodes 5, 12, 19, and 30 are leaf nodes. (b) Post-order traversal traverses Left subtree, then Right subtree, then Root. 1. Left subtree of 15: post-order of 8 gives 5, 12, 8. 2. Right subtree of 15: post-order of 24 gives 19, 30, 24. 3. Combine with root 15: 5, 12, 8, 19, 30, 24, 15.
評分準則
3 marks: Tree structure description (1 mark for root 15 with children 8 and 24; 1 mark for node 8 with children 5 and 12; 1 mark for node 24 with children 19 and 30). 2 marks: Post-order traversal sequence (2 marks for fully correct sequence: 5, 12, 8, 19, 30, 24, 15; 1 mark if only 1 or 2 minor order errors).
題目 18 · Structured Writing
5 分
Alice wants to send a secure, authentic message to Bob. Explain how Alice creates a digital signature for her message, and how Bob uses asymmetric cryptography to verify its authenticity and integrity.
查看答案詳解收起答案詳解
解題
1. Alice creates a unique, fixed-size message digest by passing her message through a cryptographic hash function. 2. Alice encrypts this message digest using her private key to produce the digital signature. 3. Alice sends both the original message and the digital signature to Bob. 4. Bob decrypts the received digital signature using Alice's public key to recover the original message digest. 5. Bob hashes the received message using the same hash function to produce a new digest. 6. Bob compares the two digests; if they match, integrity is verified (the message has not been altered) and non-repudiation is achieved (only Alice could have created the signature).
評分準則
1 mark: Alice hashes the message to create a digest. 1 mark: Alice encrypts the digest with her private key to create the signature. 1 mark: Bob decrypts the signature with Alice's public key to get the original digest. 1 mark: Bob hashes the message to get a new digest. 1 mark: Bob compares the two digests to verify integrity and authenticity.
題目 19 · Structured Writing
5 分
Compare Round Robin (RR) scheduling with Shortest Job First (SJF) scheduling. Explain how each algorithm prioritizes processes and discuss their vulnerability to process starvation.
查看答案詳解收起答案詳解
解題
1. Round Robin (RR) prioritizes processes based on a first-in, first-out cyclic queue. Each process is allocated a fixed time slice (quantum) of CPU time before being pre-empted and moved to the back of the queue. 2. Shortest Job First (SJF) prioritizes processes based on their expected CPU burst time; the process with the shortest execution time is executed first. 3. RR is completely immune to starvation because every process in the queue is guaranteed a CPU time slice in turn. 4. SJF is vulnerable to starvation because long processes may wait indefinitely if shorter processes continuously enter the ready queue. 5. This vulnerability in SJF can be mitigated using aging, which increases the priority of waiting jobs over time.
評分準則
1 mark: RR explanation of prioritization (cyclic queue with time slices/quanta). 1 mark: SJF explanation of prioritization (prioritized by shortest CPU burst/execution time). 1 mark: Explain why RR prevents starvation (fair distribution of time ensures every process gets a turn). 1 mark: Explain why SJF is vulnerable to starvation (long processes are bypassed by newer, shorter processes). 1 mark: Identify a mitigation for SJF starvation (such as aging).
題目 20 · Structured Writing
5 分
Consider the following pseudocode function: FUNCTION Calculate(Num : INTEGER) RETURNS INTEGER DECLARE Temp, Total : INTEGER; Total <- 0; WHILE Num > 0; Temp <- Num MOD 10; Total <- Total + (Temp * Temp); Num <- Num DIV 10; ENDWHILE; RETURN Total; ENDFUNCTION. Trace the execution of the function call Calculate(345) by showing the state of Num, Temp, and Total at each step, and state the final returned value.
查看答案詳解收起答案詳解
解題
1. Initial state: Num = 345, Total = 0. 2. Loop 1: Temp = 345 MOD 10 = 5. Total = 0 + (5 * 5) = 25. Num = 345 DIV 10 = 34. 3. Loop 2: Temp = 34 MOD 10 = 4. Total = 25 + (4 * 4) = 41. Num = 34 DIV 10 = 3. 4. Loop 3: Temp = 3 MOD 10 = 3. Total = 41 + (3 * 3) = 50. Num = 3 DIV 10 = 0. 5. Loop terminates as Num > 0 is false. 6. Return value is 50.
評分準則
1 mark: Correct initial state (Num=345, Total=0). 1 mark: Correct trace of Loop 1 (Temp=5, Total=25, Num=34). 1 mark: Correct trace of Loop 2 (Temp=4, Total=41, Num=3). 1 mark: Correct trace of Loop 3 (Temp=3, Total=50, Num=0). 1 mark: Correct final return value of 50.
Paper 21 (Fundamental Problem-Solving)
Answer all questions. Pseudocode and flowcharts required.
11 題目 · 76 分
題目 1 · Algorithmic Analysis / Tracing
6 分
A recursive function Process is defined as follows:
FUNCTION Process(S : STRING) RETURNS STRING DECLARE First : CHAR IF LENGTH(S) = 0 THEN RETURN "" ELSE IF LENGTH(S) = 1 THEN RETURN S ELSE First <- MID(S, 1, 1) IF First = "A" OR First = "E" OR First = "I" OR First = "O" OR First = "U" THEN RETURN Process(MID(S, 2, LENGTH(S) - 1)) & First ELSE RETURN First & Process(MID(S, 2, LENGTH(S) - 1)) ENDIF ENDIF ENDIF ENDFUNCTION
(a) Trace the execution of the function call Process("CAMBRIDGE"). Show the recursive call stack by listing each call to Process and its return value. [4 marks] (b) Explain the overall purpose of this recursive function. [2 marks]
查看答案詳解收起答案詳解
解題
Step-by-step trace of recursive calls: 1. Process("CAMBRIDGE") -> 'C' is not a vowel -> Returns "C" & Process("AMBRIDGE") 2. Process("AMBRIDGE") -> 'A' is a vowel -> Returns Process("MBRIDGE") & "A" 3. Process("MBRIDGE") -> 'M' is not a vowel -> Returns "M" & Process("BRIDGE") 4. Process("BRIDGE") -> 'B' is not a vowel -> Returns "B" & Process("RIDGE") 5. Process("RIDGE") -> 'R' is not a vowel -> Returns "R" & Process("IDGE") 6. Process("IDGE") -> 'I' is a vowel -> Returns Process("DGE") & "I" 7. Process("DGE") -> 'D' is not a vowel -> Returns "D" & Process("GE") 8. Process("GE") -> 'G' is not a vowel -> Returns "G" & Process("E") 9. Process("E") -> Length is 1 -> Returns "E"
(a) Call stack and return trace: [4 marks] - 1 mark for correct base case return value ("E"). - 1 mark for showing correct vowel shifting mechanism (e.g., 'A' and 'I' appended at the end of their sub-results). - 1 mark for correct intermediate strings for at least 4 recursive steps. - 1 mark for correct final output "CMBRDGEIA". (b) Overall purpose: [2 marks] - 1 mark for stating that it filters and moves all vowels to the end of the string. - 1 mark for noting that consonants retain their original relative positions while vowels are shifted to the back.
題目 2 · Algorithmic Analysis / Tracing
6 分
The following pseudocode represents an algorithm designed to rearrange elements in an array:
PROCEDURE Rearrange(BYREF Arr : ARRAY OF INTEGER, Size : INTEGER) DECLARE I, J, Temp : INTEGER DECLARE Swapped : BOOLEAN I <- 1 REPEAT Swapped <- FALSE FOR J <- 1 TO Size - I IF Arr[J] < Arr[J + 1] THEN Temp <- Arr[J] Arr[J] <- Arr[J + 1] Arr[J + 1] <- Temp Swapped <- TRUE ENDIF ENDFOR I <- I + 1 UNTIL NOT Swapped OR I = Size ENDPROCEDURE
Trace the execution of this procedure with Size = 5 and the initial array contents: Arr[1] = 12, Arr[2] = 45, Arr[3] = 23, Arr[4] = 56, Arr[5] = 17
Complete the trace table below by showing the value of I, Swapped, and the state of Arr after each outer loop pass (when the inner FOR loop completes).
查看答案詳解收起答案詳解
解題
Let's trace each outer loop pass step-by-step: - Pass 1 (I = 1): Inner loop J goes from 1 to 4. - J=1: Arr[1](12) < Arr[2](45) is TRUE -> Swap. Arr becomes [45, 12, 23, 56, 17], Swapped = TRUE. - J=2: Arr[2](12) < Arr[3](23) is TRUE -> Swap. Arr becomes [45, 23, 12, 56, 17], Swapped = TRUE. - J=3: Arr[3](12) < Arr[4](56) is TRUE -> Swap. Arr becomes [45, 23, 56, 12, 17], Swapped = TRUE. - J=4: Arr[4](12) < Arr[5](17) is TRUE -> Swap. Arr becomes [45, 23, 56, 17, 12], Swapped = TRUE. - End of Pass 1: Arr = [45, 23, 56, 17, 12], I increments to 2. - Pass 2 (I = 2): Inner loop J goes from 1 to 3. - J=1: Arr[1](45) < Arr[2](23) is FALSE. - J=2: Arr[2](23) < Arr[3](56) is TRUE -> Swap. Arr becomes [45, 56, 23, 17, 12], Swapped = TRUE. - J=3: Arr[3](23) < Arr[4](17) is FALSE. - End of Pass 2: Arr = [45, 56, 23, 17, 12], I increments to 3. - Pass 3 (I = 3): Inner loop J goes from 1 to 2. - J=1: Arr[1](45) < Arr[2](56) is TRUE -> Swap. Arr becomes [56, 45, 23, 17, 12], Swapped = TRUE. - J=2: Arr[2](45) < Arr[3](23) is FALSE. - End of Pass 3: Arr = [56, 45, 23, 17, 12], I increments to 4. - Pass 4 (I = 4): Inner loop J goes from 1 to 1. - J=1: Arr[1](56) < Arr[2](45) is FALSE. Swapped remains FALSE. - End of Pass 4: Arr = [56, 45, 23, 17, 12], I increments to 5. Loop terminates because Swapped is FALSE (and I = Size).
評分準則
Trace Table Marks: [6 marks total] - 1 mark for correct array values and Swapped=TRUE at the end of Pass 1. - 1 mark for correct array values and Swapped=TRUE at the end of Pass 2. - 1 mark for correct array values and Swapped=TRUE at the end of Pass 3. - 1 mark for correct array values and Swapped=FALSE at the end of Pass 4. - 1 mark for correct outer loop counter values of I (1, 2, 3, 4). - 1 mark for showing correct exit condition (Swapped = FALSE at Pass 4).
題目 3 · Algorithmic Analysis / Tracing
6 分
A circular queue is implemented using a 1D array Q[1..5] of size 5, with two global pointers Front and Rear both initialized to 0.
The operations are defined below:
PROCEDURE Enqueue(Item : INTEGER) IF (Rear MOD 5) + 1 = Front THEN OUTPUT "Queue Full" ELSE IF Front = 0 THEN Front <- 1 ENDIF Rear <- (Rear MOD 5) + 1 Q[Rear] <- Item ENDIF ENDPROCEDURE
FUNCTION Dequeue() RETURNS INTEGER DECLARE Item : INTEGER IF Front = 0 THEN OUTPUT "Queue Empty" RETURN -1 ELSE Item <- Q[Front] IF Front = Rear THEN Front <- 0 Rear <- 0 ELSE Front <- (Front MOD 5) + 1 ENDIF RETURN Item ENDIF ENDFUNCTION
Trace the execution of the following sequence of operations, starting with an empty queue (Front = 0, Rear = 0, and Q = [0, 0, 0, 0, 0]):
Provide the final state of: (a) The values of pointers Front and Rear [2 marks] (b) The contents of the array Q [2 marks] (c) The values stored in variables X and Y [2 marks]
查看答案詳解收起答案詳解
解題
Detailed step-by-step trace: - Start: Front = 0, Rear = 0, Q = [0, 0, 0, 0, 0] 1. Enqueue(10): Front becomes 1, Rear becomes 1. Q[1] = 10. Q = [10, 0, 0, 0, 0] 2. Enqueue(20): Rear becomes 2. Q[2] = 20. Q = [10, 20, 0, 0, 0] 3. X <- Dequeue(): Front is 1. Item = Q[1] = 10. Front becomes 2. X = 10. 4. Enqueue(30): Rear becomes 3. Q[3] = 30. Q = [10, 20, 30, 0, 0] 5. Enqueue(40): Rear becomes 4. Q[4] = 40. Q = [10, 20, 30, 40, 0] 6. Enqueue(50): Rear becomes 5. Q[5] = 50. Q = [10, 20, 30, 40, 50] 7. Enqueue(60): (5 MOD 5) + 1 = 1. Since 1 != Front (2), not full. Rear becomes 1. Q[1] = 60. Q = [60, 20, 30, 40, 50] 8. Y <- Dequeue(): Front is 2. Item = Q[2] = 20. Front becomes 3. Y = 20. 9. Enqueue(70): (1 MOD 5) + 1 = 2. Since 2 != Front (3), not full. Rear becomes 2. Q[2] = 70. Q = [60, 70, 30, 40, 50]
Final values: - Front = 3, Rear = 2 - Q = [60, 70, 30, 40, 50] - X = 10, Y = 20
評分準則
- (a) 1 mark for Front = 3, 1 mark for Rear = 2. - (b) 2 marks for correct array contents [60, 70, 30, 40, 50]. Deduct 1 mark if either element 60 or 70 is placed in the wrong index. - (c) 1 mark for X = 10, 1 mark for Y = 20.
題目 4 · Algorithmic Analysis / Tracing
6 分
The following procedure decodes a custom-encoded message string:
FOR I <- 1 TO LENGTH(Msg) - 1 Ch <- MID(Msg, I, 1) IF Ch >= "A" AND Ch <= "Z" THEN CodeVal <- ASC(Ch) - Key IF CodeVal < ASC("A") THEN CodeVal <- CodeVal + 26 ENDIF Ch <- CHR(CodeVal) ENDIF Out <- Out & Ch ENDFOR OUTPUT Out ENDPROCEDURE
Note: - VALUE(S) converts a numeric string to its integer value. - RIGHT(S, N) extracts the last N characters of string S. - MID(S, Start, Len) extracts a substring starting at Start with length Len. - ASC(Ch) returns the ASCII value of character Ch (e.g., ASC("A") = 65, ASC("B") = 66, ..., ASC("Z") = 90). - CHR(Val) returns the character represented by ASCII value Val.
Trace the execution of Decode("BZA4") by completing the trace table below showing I, Ch, CodeVal, and Out.
查看答案詳解收起答案詳解
解題
- Input: Msg = "BZA4" - Key = VALUE(RIGHT("BZA4", 1)) = VALUE("4") = 4 - Out = "" - Loop I from 1 to LENGTH(Msg) - 1 = 3: - Pass 1 (I = 1): - Ch = MID("BZA4", 1, 1) = "B" - CodeVal = ASC("B") - 4 = 66 - 4 = 62 - Since CodeVal < 65, CodeVal = 62 + 26 = 88 - Ch = CHR(88) = "X" - Out = "" & "X" = "X" - Pass 2 (I = 2): - Ch = MID("BZA4", 2, 1) = "Z" - CodeVal = ASC("Z") - 4 = 90 - 4 = 86 - CodeVal is not less than 65 - Ch = CHR(86) = "V" - Out = "X" & "V" = "XV" - Pass 3 (I = 3): - Ch = MID("BZA4", 3, 1) = "A" - CodeVal = ASC("A") - 4 = 65 - 4 = 61 - Since CodeVal < 65, CodeVal = 61 + 26 = 87 - Ch = CHR(87) = "W" - Out = "XV" & "W" = "XVW" - Output printed: "XVW"
評分準則
- 1 mark for correctly extracting Key = 4. - 1 mark for correct I = 1 row (Ch = "B", CodeVal = 88, Out = "X"). - 1 mark for correct I = 2 row (Ch = "Z", CodeVal = 86, Out = "XV"). - 1 mark for correct I = 3 row (Ch = "A", CodeVal = 87, Out = "XVW"). - 1 mark for correctly performing the ASCII boundary wrap-around logic (+26) for "B" and "A". - 1 mark for the correct final output "XVW".
題目 5 · Algorithmic Analysis / Tracing
6 分
A binary search tree is implemented using three global 1D arrays of size 7: LeftPointer, Data, and RightPointer. The tree contains the following data:
PROCEDURE Traverse(NodeIndex : INTEGER) IF NodeIndex <> 0 THEN IF LeftPointer[NodeIndex] <> 0 THEN Traverse(LeftPointer[NodeIndex]) ENDIF IF RightPointer[NodeIndex] <> 0 THEN Traverse(RightPointer[NodeIndex]) ENDIF OUTPUT Data[NodeIndex] ENDIF ENDPROCEDURE
(a) Show the sequence of procedure calls made by Traverse(RootPointer) in the order they are called. [3 marks] (b) Give the complete output sequence of this procedure. [2 marks] (c) State the type of tree traversal this procedure performs. [1 mark]
查看答案詳解收起答案詳解
解題
(a) Step-by-step calls: 1. Traverse(1) is called. 2. Traverse(1) calls Traverse(LeftPointer[1]) which is Traverse(2). 3. Traverse(2) calls Traverse(LeftPointer[2]) which is Traverse(4). 4. Traverse(4) has no children, so it outputs "B" and returns to Traverse(2). 5. Traverse(2) calls Traverse(RightPointer[2]) which is Traverse(5). 6. Traverse(5) has no children, so it outputs "H" and returns to Traverse(2). 7. Traverse(2) outputs "F" and returns to Traverse(1). 8. Traverse(1) calls Traverse(RightPointer[1]) which is Traverse(3). 9. Traverse(3) calls Traverse(LeftPointer[3]) which is Traverse(6). 10. Traverse(6) outputs "P" and returns to Traverse(3). 11. Traverse(3) calls Traverse(RightPointer[3]) which is Traverse(7). 12. Traverse(7) outputs "T" and returns to Traverse(3). 13. Traverse(3) outputs "R" and returns to Traverse(1). 14. Traverse(1) outputs "M".
(b) Output sequence: "B", "H", "F", "P", "T", "R", "M". (c) The traversal is post-order because it recursively processes the left subtree, then the right subtree, and finally outputs the root node.
評分準則
(a) Sequence of calls: [3 marks] - 1 mark for correct first three calls in order: Traverse(1), Traverse(2), Traverse(4). - 1 mark for next two calls: Traverse(5), Traverse(3). - 1 mark for final two calls: Traverse(6), Traverse(7). (b) Output sequence: [2 marks] - 1 mark for correct first three outputs: "B", "H", "F". - 1 mark for remaining correct outputs: "P", "T", "R", "M". (c) Traversal type: [1 mark] - 1 mark for "Post-order" (or "postorder").
題目 6 · Algorithmic Analysis / Tracing
6 分
The following function implements a modified search algorithm known as a Jump Search on a sorted array of integers:
FUNCTION JumpSearch(Arr : ARRAY OF INTEGER, Target : INTEGER, Size : INTEGER) RETURNS INTEGER DECLARE Step, Prev, I : INTEGER Step <- 3 Prev <- 1
WHILE Arr[MIN(Step, Size)] < Target DO Prev <- Step Step <- Step + 3 IF Prev >= Size THEN RETURN -1 ENDIF ENDWHILE
I <- Prev WHILE Arr[I] < Target DO I <- I + 1 IF I = MIN(Step + 1, Size + 1) THEN RETURN -1 ENDIF ENDWHILE
IF Arr[I] = Target THEN RETURN I ELSE RETURN -1 ENDIF ENDFUNCTION
An array Arr of size 10 contains: [10, 15, 20, 25, 30, 35, 40, 45, 50, 55]
(a) Trace the execution of JumpSearch(Arr, 35, 10). State the values of variables Prev and Step when the first WHILE loop terminates, and the final value of I. [3 marks] (b) Trace the execution of JumpSearch(Arr, 22, 10). Explain what value is returned and how the second WHILE loop determines that the element is not in the array. [3 marks]
查看答案詳解收起答案詳解
解題
(a) Tracing JumpSearch(Arr, 35, 10): - Initial: Step = 3, Prev = 1. - First loop condition: Arr[MIN(3,10)] < 35 -> Arr[3] < 35 -> 20 < 35 is TRUE. - Prev becomes 3, Step becomes 6. - Next loop condition: Arr[MIN(6,10)] < 35 -> Arr[6] < 35 -> 35 < 35 is FALSE. - First loop terminates with Prev = 3, Step = 6. - Second part: I starts at 3. - Arr[3](20) < 35 is TRUE -> I becomes 4. - Arr[4](25) < 35 is TRUE -> I becomes 5. - Arr[5](30) < 35 is TRUE -> I becomes 6. - Arr[6](35) < 35 is FALSE -> second loop terminates with I = 6. - Check: Arr[6] = 35 is TRUE -> returns 6.
(b) Tracing JumpSearch(Arr, 22, 10): - Initial: Step = 3, Prev = 1. - First loop condition: Arr[3](20) < 22 is TRUE. - Prev becomes 3, Step becomes 6. - Next condition: Arr[6](35) < 22 is FALSE -> first loop terminates. - Second part: I starts at 3. - Arr[3](20) < 22 is TRUE -> I becomes 4. - Next condition: Arr[4](25) < 22 is FALSE -> second loop terminates. - Check: Arr[4] = 22 is FALSE -> returns -1. - Explanation: The first loop successfully localized the potential target to the range [3..6]. When linear search starts at index 3, it inspects Arr[4] which is 25. Since 25 > 22, and the array is sorted, no subsequent items can equal 22. The loop condition Arr[I] < Target fails immediately, allowing the algorithm to stop early.
評分準則
(a) Trace for Target = 35: [3 marks] - 1 mark for Prev = 3 at termination of first loop. - 1 mark for Step = 6 at termination of first loop. - 1 mark for final index I = 6 (and returns 6). (b) Trace for Target = 22: [3 marks] - 1 mark for stating that the function returns -1. - 1 mark for noting that the second loop terminates because Arr[4] = 25 is greater than 22 (the condition Arr[I] < 22 is violated). - 1 mark for explaining that because the array is sorted, any value past 25 will also be larger than 22, proving 22 is not present.
題目 7 · Pseudocode Design
8 分
A teacher needs to identify the student with the highest average test score in a class of 50 students. The marks for the students in 5 different tests are stored in a global 2D array named Grades of type INTEGER, which is declared as:
DECLARE Grades : ARRAY[1:50, 1:5] OF INTEGER
Write a pseudocode function FindHighestAverage() that returns the 1-based index (row number) of the student with the highest average score across the 5 tests. If more than one student shares the highest average, the function should return the index of the first student with that score.
Your pseudocode must include appropriate variable declarations, loop structures, and comply with Cambridge standard pseudocode.
查看答案詳解收起答案詳解
解題
The function calculates the average score for each student by summing up their grades across 5 subjects and dividing by 5.0. It compares each student's average to the current maximum average. If a student's average is strictly greater than the current maximum, the maximum average is updated and the student's index is stored. This ensures that in the case of a tie, the first student with that average is preserved.
Pseudocode: ``` FUNCTION FindHighestAverage() RETURNS INTEGER DECLARE Student, Test : INTEGER DECLARE Sum : INTEGER DECLARE Average, MaxAverage : REAL DECLARE BestStudent : INTEGER
MaxAverage <- -1.0 BestStudent <- 1
FOR Student <- 1 TO 50 Sum <- 0 FOR Test <- 1 TO 5 Sum <- Sum + Grades[Student, Test] NEXT Test Average <- Sum / 5.0 IF Average > MaxAverage THEN MaxAverage <- Average BestStudent <- Student ENDIF NEXT Student
RETURN BestStudent ENDFUNCTION ```
評分準則
- 1 mark: Correct function header and return type (RETURNS INTEGER). - 1 mark: Correctly declaring all local variables (Student, Test, Sum, Average, MaxAverage, BestStudent) with appropriate data types. - 1 mark: Initialising MaxAverage to -1.0 (or another low value) and BestStudent before processing. - 1 mark: Outer loop iterating through 50 students correctly. - 1 mark: Inner loop iterating through 5 tests for each student correctly. - 1 mark: Calculating the sum and the average score (Sum / 5.0) accurately. - 1 mark: Comparing Average > MaxAverage and updating MaxAverage and BestStudent if true. - 1 mark: Returning the correct BestStudent index and terminating the function properly.
題目 8 · Pseudocode Design
8 分
Write a pseudocode function ValidatePassword(Password : STRING) RETURNS BOOLEAN that validates a password string based on the following requirements: - The password length must be between 8 and 16 characters inclusive. - It must contain at least one uppercase character ('A'-'Z'). - It must contain at least one lowercase character ('a'-'z'). - It must contain at least one digit ('0'-'9').
The function must return TRUE if the password meets all criteria, and FALSE otherwise.
You should assume that standard string functions LENGTH(s : STRING) RETURNS INTEGER and MID(s : STRING, start : INTEGER, length : INTEGER) RETURNS STRING are available.
查看答案詳解收起答案詳解
解題
The algorithm first checks the length of the string. If it's outside the valid range [8, 16], it returns FALSE. It then scans each character using a FOR loop with MID. It marks boolean flags when matching characters are found. Finally, it returns TRUE only if all three flags are TRUE.
FOR i <- 1 TO PassLength Char <- MID(Password, i, 1) IF Char >= "A" AND Char <= "Z" THEN HasUpper <- TRUE ELSEIF Char >= "a" AND Char <= "z" THEN HasLower <- TRUE ELSEIF Char >= "0" AND Char <= "9" THEN HasDigit <- TRUE ENDIF NEXT i
IF HasUpper AND HasLower AND HasDigit THEN RETURN TRUE ELSE RETURN FALSE ENDIF ENDFUNCTION ```
評分準則
- 1 mark: Correct function header with parameter Password : STRING and RETURNS BOOLEAN. - 1 mark: Length check of Password using LENGTH() to ensure it is between 8 and 16 characters inclusive. - 1 mark: Declaring and initializing three boolean flags (HasUpper, HasLower, HasDigit) to FALSE. - 1 mark: Correct loop structure (FOR i <- 1 TO PassLength) to traverse every character. - 1 mark: Extracting single character using MID(Password, i, 1). - 1 mark: Checking character range for uppercase ('A' to 'Z') and lowercase ('a' to 'z') and setting corresponding flags. - 1 mark: Checking character range for digit ('0' to '9') and setting corresponding flag. - 1 mark: Returning TRUE if and only if all criteria are satisfied, otherwise returning FALSE.
題目 9 · Pseudocode Design
8 分
A queue data structure is implemented using a 1D circular array of size 10, indexed from 0 to 9. The queue stores integers. The following global variables have been declared: - Queue : ARRAY[0:9] OF INTEGER - Head : INTEGER (points to the front element) - Tail : INTEGER (points to the rear element) - NumItems : INTEGER (the count of items in the queue)
Initially, Head = 0, Tail = -1, and NumItems = 0.
Write a pseudocode function Enqueue(Value : INTEGER) RETURNS BOOLEAN that attempts to insert an element into this queue. If successful, it updates the appropriate variables and returns TRUE. If the queue is full, it returns FALSE and does not modify the queue elements. Note that the Tail pointer must wrap around to 0 when it exceeds 9.
查看答案詳解收起答案詳解
解題
To add an element to a circular queue, we first check if the queue is full by comparing NumItems to the maximum size of the array (10). If full, the function returns FALSE. If not full, we increment the Tail index using modular arithmetic (Tail <- (Tail + 1) MOD 10) to handle the wrap-around. We then insert the Value at Queue[Tail], increment NumItems by 1, and return TRUE.
Pseudocode: ``` FUNCTION Enqueue(Value : INTEGER) RETURNS BOOLEAN IF NumItems = 10 THEN RETURN FALSE ENDIF
Tail <- (Tail + 1) MOD 10 Queue[Tail] <- Value NumItems <- NumItems + 1
RETURN TRUE ENDFUNCTION ```
評分準則
- 1 mark: Correct function header with correct parameters and return type. - 2 marks: Correctly checking if the queue is full (comparing NumItems to 10) and returning FALSE if so. - 2 marks: Correct circular wrapping formula for Tail (either Tail <- (Tail + 1) MOD 10 or using an IF block: Tail <- Tail + 1; IF Tail = 10 THEN Tail <- 0 ENDIF). - 1 mark: Storing the element in Queue at index Tail. - 1 mark: Incrementing NumItems by 1. - 1 mark: Returning TRUE at the end.
題目 10 · Pseudocode Design
8 分
Write a pseudocode function BinarySearch(SearchList : ARRAY[1:100] OF STRING, Item : STRING) RETURNS INTEGER that searches for Item in a sorted 1D array of strings SearchList.
If Item is found, the function must return its 1-based index (between 1 and 100). If the item is not found, the function must return -1.
Your pseudocode must use a loop structure and implement the standard binary search algorithm, maintaining lower, upper, and midpoint boundaries.
查看答案詳解收起答案詳解
解題
A binary search works by continually dividing the search space in half. We initialize Lower to 1 and Upper to 100. Inside the WHILE loop, we compute Mid as the integer division of (Lower + Upper). We compare SearchList[Mid] with Item. If they are equal, we terminate the loop. If SearchList[Mid] is greater than Item, we adjust the Upper boundary to Mid - 1. Otherwise, we adjust the Lower boundary to Mid + 1. If Found is true, we return Mid; otherwise, -1.
Pseudocode: ``` FUNCTION BinarySearch(SearchList : ARRAY[1:100] OF STRING, Item : STRING) RETURNS INTEGER DECLARE Lower, Upper, Mid : INTEGER DECLARE Found : BOOLEAN
Lower <- 1 Upper <- 100 Found <- FALSE Mid <- -1
WHILE Lower <= Upper AND NOT Found Mid <- (Lower + Upper) DIV 2 IF SearchList[Mid] = Item THEN Found <- TRUE ELSEIF SearchList[Mid] > Item THEN Upper <- Mid - 1 ELSE Lower <- Mid + 1 ENDIF ENDWHILE
IF Found THEN RETURN Mid ELSE RETURN -1 ENDIF ENDFUNCTION ```
評分準則
- 1 mark: Correct function header with correct parameters and RETURNS INTEGER. - 1 mark: Initializing Lower to 1 and Upper to 100. - 1 mark: Loop with correct termination condition (Lower <= Upper AND NOT Found). - 1 mark: Correct calculation of Mid using integer division (DIV or equivalent). - 1 mark: Correct conditional statement checking if SearchList[Mid] is equal to Item. - 1 mark: Correctly updating Upper <- Mid - 1 if SearchList[Mid] > Item. - 1 mark: Correctly updating Lower <- Mid + 1 if SearchList[Mid] < Item. - 1 mark: Returning Mid if found, otherwise returning -1.
題目 11 · Pseudocode Design
8 分
A text file SalesData.txt contains records of daily transactions. Each line in the file stores a salesperson ID (a string of length 5) followed by a comma, and then the transaction amount (a real number represented as a string). For example: "SP004,124.50".
Write a pseudocode procedure SummariseSales(FileName : STRING) that reads and processes this file line by line. The procedure must: 1. Open the file in read mode. 2. Loop through the file until EOF is reached. 3. Extract the transaction amount substring starting from character position 7 to the end of the line, convert it to a real number, and add it to a running total. 4. Keep track of the total number of transactions. 5. Close the file. 6. Output the total sales amount and the average sale amount to the screen in the format: "Total Sales: $X" "Average Sale: $Y" If no transactions are processed because the file is empty, it must output the message: "No transactions found".
You should assume standard file operations: OPENFILE FOR READ, READFILE , , CLOSEFILE , and EOF() are available. Also assume TONUM(s : STRING) RETURNS REAL is available to convert a string to a numeric value, and LENGTH(s) and MID(s, start, length) are available.
查看答案詳解收起答案詳解
解題
The procedure opens the specified file and uses a loop checking EOF to process all lines. For each non-empty line, it extracts the transaction amount (since the salesperson ID and comma take exactly 6 characters, the amount starts at index 7). It then converts the string to a real number using TONUM(), adds it to the running sum, and increments the count. After reading the whole file, it closes the file and outputs the calculated values, handling the division-by-zero risk if the file was empty.
WHILE NOT EOF(FileName) READFILE FileName, Line IF Line <> "" THEN AmountStr <- MID(Line, 7, LENGTH(Line) - 6) Amount <- TONUM(AmountStr) Total <- Total + Amount Count <- Count + 1 ENDIF ENDWHILE
CLOSEFILE FileName
IF Count > 0 THEN OUTPUT "Total Sales: $", Total OUTPUT "Average Sale: $", (Total / Count) ELSE OUTPUT "No transactions found" ENDIF ENDPROCEDURE ```
評分準則
- 1 mark: Correct procedure header (PROCEDURE SummariseSales(FileName : STRING)) and local declarations. - 1 mark: Correct syntax to open and close the file (OPENFILE ... FOR READ and CLOSEFILE ...). - 1 mark: Using a WHILE loop with EOF(FileName) to read all lines correctly. - 1 mark: Using READFILE to read line-by-line. - 1 mark: Extracting the amount substring using MID(Line, 7, LENGTH(Line) - 6) or equivalent logic. - 1 mark: Converting the extracted string to a REAL value using TONUM(). - 1 mark: Keeping a running total and counting transactions. - 1 mark: Formatting output messages correctly, including handling of empty files with an appropriate IF-ELSE check.
Paper 31 (Advanced Theory)
Answer all questions. Core mathematical, network and database theory.
15 題目 · 75 分
題目 1 · Calculation / Mapping
5 分
A real number is stored in a 12-bit floating-point format. The format consists of an 8-bit mantissa followed by a 4-bit exponent. Both the mantissa and the exponent are represented in two's complement. The binary representation of the floating-point number is: 10110000 0101. Calculate the denary equivalent of this binary floating-point representation, showing the details of your working.
查看答案詳解收起答案詳解
解題
1. Separate the mantissa and exponent: Mantissa = 10110000, Exponent = 0101. 2. Calculate the exponent value: Since the exponent 0101 is positive, it equals 1 * 2^2 + 1 * 2^0 = 4 + 1 = 5. 3. Calculate the mantissa value: The mantissa is negative because the sign bit is 1. Convert to two's complement to find its magnitude: flip bits to get 01001111, then add 1 to get 01010000. This represents the binary fraction 0.1010000, which has the denary value 0.5 + 0.125 = 0.625. Thus, the actual value of the mantissa is -0.625. Alternatively, using negative weights: -1 * 2^0 + 0 * 2^-1 + 1 * 2^-2 + 1 * 2^-3 = -1 + 0.25 + 0.125 = -0.625. 4. Multiply the mantissa by 2 raised to the exponent: Value = -0.625 * 2^5 = -0.625 * 32 = -20.
評分準則
1 mark: Correctly identifies exponent binary '0101' as denary 5. 1 mark: Shows correct conversion of negative mantissa to a denary fraction (e.g., via bit flipping or using negative weight of MSB). 1 mark: Obtains correct denary value of the mantissa as -0.625. 1 mark: Shows the calculation of multiplying the mantissa by 2 raised to the power of the exponent (e.g., -0.625 * 32). 1 mark: Obtains correct final answer of -20.
題目 2 · Calculation / Mapping
5 分
An IPv4 network packet with the destination IP address 192.168.67.85 arrives at a router. The router's routing table has the following active entries: Route A: 192.168.64.0/18; Route B: 192.168.64.0/22; Route C: 192.168.66.0/23; Route D: 0.0.0.0/0 (Default Gateway). Perform the subnet masking calculations for Route A, Route B, and Route C to show which routes match the packet's destination IP address. State which route the router will select and explain why.
查看答案詳解收起答案詳解
解題
1. Convert the third octet of the destination IP (67) to binary: 67 = 01000011. 2. For Route A (192.168.64.0/18): The mask /18 has 18 ones, meaning the third octet mask is 11000000 (192). Perform bitwise AND: 01000011 AND 11000000 = 01000000 (64). Resulting network address is 192.168.64.0. This matches. 3. For Route B (192.168.64.0/22): The mask /22 has 22 ones, meaning the third octet mask is 11111100 (252). Perform bitwise AND: 01000011 AND 11111100 = 01000000 (64). Resulting network address is 192.168.64.0. This matches. 4. For Route C (192.168.66.0/23): The mask /23 has 23 ones, meaning the third octet mask is 11111110 (254). Perform bitwise AND: 01000011 AND 11111110 = 01000010 (66). Resulting network address is 192.168.66.0. This matches. 5. Selection: Route C is selected. Although Route A, Route B, and Route C all match, Route C has the longest prefix match (/23 is the most specific mask).
評分準則
1 mark: Shows subnet calculation for Route A resulting in 192.168.64.0 (matching). 1 mark: Shows subnet calculation for Route B resulting in 192.168.64.0 (matching). 1 mark: Shows subnet calculation for Route C resulting in 192.168.66.0 (matching). 1 mark: Identifies Route C as the chosen route. 1 mark: Explains that Route C is selected because it is the longest prefix match (most specific subnet mask).
題目 3 · Calculation / Mapping
5 分
Show the state of a stack during the evaluation of the following Reverse Polish Notation (RPN) expression: 8 3 2 * - 5 4 + * . Identify the contents of the stack immediately after each of the four operator operations is performed. Assume the stack grows from left to right (so the rightmost element is the top of the stack). State the final evaluated value of the expression.
查看答案詳解收起答案詳解
解題
We evaluate the expression step-by-step: 1. Push 8: [8]; 2. Push 3: [8, 3]; 3. Push 2: [8, 3, 2]; 4. Operator '*': Pop 2 and Pop 3. Calculate 3 * 2 = 6. Push 6. Stack state: [8, 6]; 5. Operator '-': Pop 6 and Pop 8. Calculate 8 - 6 = 2. Push 2. Stack state: [2]; 6. Push 5: [2, 5]; 7. Push 4: [2, 5, 4]; 8. Operator '+': Pop 4 and Pop 5. Calculate 5 + 4 = 9. Push 9. Stack state: [2, 9]; 9. Operator '*': Pop 9 and Pop 2. Calculate 2 * 9 = 18. Push 18. Stack state: [18]. The final evaluated value is 18.
評分準則
1 mark: Correct stack state after the first operator '*': [8, 6]. 1 mark: Correct stack state after the operator '-': [2]. 1 mark: Correct stack state after the operator '+': [2, 9]. 1 mark: Correct stack state after the final operator '*': [18]. 1 mark: Correctly states the final value is 18.
題目 4 · Calculation / Mapping
5 分
A Boolean logic system has four inputs: A, B, C, and D. The output of the system is 1 for the following combinations of inputs: \(\bar{A}\bar{B}CD\), \(\bar{A}\bar{B}C\bar{D}\), \(\bar{A}BCD\), \(\bar{A}BC\bar{D}\), \(AB\bar{C}\bar{D}\), \(ABC\bar{D}\), \(A\bar{B}\bar{C}\bar{D}\), and \(A\bar{B}C\bar{D}\). (a) Map these 1s onto a 4-variable Karnaugh Map (K-map) with rows labeled AB (00, 01, 11, 10) and columns labeled CD (00, 01, 11, 10). (b) Using the K-map, identify the loops of size 4 and write the final simplified sum-of-products expression.
查看答案詳解收起答案詳解
解題
(a) Map the terms: \(\bar{A}\bar{B}CD\) -> Row 00, Col 11; \(\bar{A}\bar{B}C\bar{D}\) -> Row 00, Col 10; \(\bar{A}BCD\) -> Row 01, Col 11; \(\bar{A}BC\bar{D}\) -> Row 01, Col 10; \(AB\bar{C}\bar{D}\) -> Row 11, Col 00; \(ABC\bar{D}\) -> Row 11, Col 10; \(A\bar{B}\bar{C}\bar{D}\) -> Row 10, Col 00; \(A\bar{B}C\bar{D}\) -> Row 10, Col 10. (b) Identify groups of size 4: Group 1: Consists of the four 1s in rows 00 and 01, columns 11 and 10. These represent the terms \(\bar{A}\bar{B}C\) and \(\bar{A}BC\). The variable B changes state, so it is eliminated, leaving \(\bar{A}C\). Group 2: Consists of the four 1s in rows 11 and 10, columns 00 and 10. This is the corners/edges on the bottom half. Since the rows are 11 and 10, B changes and is eliminated, leaving A. The columns are 00 and 10, C changes and is eliminated, leaving \(\bar{D}\). This group simplifies to \(A\bar{D}\). All 1s are now covered by these two groups of size 4. Hence, the simplified expression is: \(\bar{A}C + A\bar{D}\).
評分準則
2 marks: Correctly maps all 8 of the 1s in the K-map (1 mark if 6 or 7 are correct). 2 marks: Identifies the two optimal loops of size 4 (1 mark for group \(\bar{A}C\), 1 mark for group \(A\bar{D}\)). 1 mark: Correctly combines the terms into the final simplified Boolean expression: \(\bar{A}C + A\bar{D}\).
題目 5 · Calculation / Mapping
5 分
An asymmetric cryptosystem uses the RSA algorithm. A key pair is generated using two prime numbers p = 3 and q = 11. (a) Calculate the modulus n and the Euler totient function \(\phi(n)\). (b) Given the public exponent e = 3, calculate the private key d using the modular inverse equation: \((d \times e) \pmod{\phi(n)} = 1\). (c) A user wishes to encrypt the plaintext message M = 4. Calculate the resulting ciphertext C.
查看答案詳解收起答案詳解
解題
(a) Modulus n = p * q = 3 * 11 = 33. Totient \(\phi(n)\) = (p - 1) * (q - 1) = 2 * 10 = 20. (b) Find d such that \((d \times 3) \pmod{20} = 1\). We can check values of d: d = 1: 3 mod 20 = 3; d = 7: 21 mod 20 = 1. Thus, d = 7. (c) Encrypt plaintext M = 4: \(C = M^e \pmod{n} = 4^3 \pmod{33} = 64 \pmod{33}\). 64 = 1 * 33 + 31. So, C = 31.
評分準則
1 mark: Correctly calculates n = 33. 1 mark: Correctly calculates \(\phi(n)\) = 20. 1 mark: Correctly finds private key d = 7 with appropriate working. 1 mark: Writes the correct encryption formula \(C = 4^3 \pmod{33}\). 1 mark: Correctly calculates final ciphertext C = 31.
題目 6 · Calculation / Mapping
5 分
A 12-bit floating-point representation has an 8-bit mantissa and a 4-bit exponent, both represented in two's complement. The following non-normalized binary representation is given: Mantissa: 0.0001100, Exponent: 0110. (a) Show that the denary value of this representation is 6.0. (b) Normalize this binary floating-point representation. Show your working by explaining how the mantissa and exponent change, and state the final binary representations of both.
查看答案詳解收起答案詳解
解題
(a) Calculate denary value: Mantissa: 0.0001100. Binary point is after the first bit. The 1s are at positions \(2^{-4}\) (1/16) and \(2^{-5}\) (1/32). Value = 1/16 + 1/32 = 3/32 = 0.09375. Exponent: 0110. This is positive, so it equals 4 + 2 = 6. Value = \(0.09375 \times 2^6 = 0.09375 \times 64 = 6.0\). (b) Normalize the representation: For a positive floating-point number to be normalized, the mantissa must start with '0.1'. To achieve this, shift the mantissa three places to the left: 0.0001100 -> 0.1100000. To compensate for shifting the mantissa left by three, we must subtract 3 from the exponent: Exponent = 6 - 3 = 3. Convert the new exponent 3 to 4-bit two's complement: 0011. Final normalized values: Mantissa = 0.1100000, Exponent = 0011.
評分準則
1 mark: Shows working for denary value: Mantissa = 0.09375, Exponent = 6, and value = 6.0. 1 mark: Identifies that a normalized positive mantissa must begin with '0.1'. 1 mark: Shifts the mantissa three places to the left to obtain 0.1100000. 1 mark: Decrements the exponent by 3 to compensate for the shift, resulting in 3. 1 mark: States the correct final binary representations: Mantissa = 0.1100000, Exponent = 0011.
題目 7 · Calculation / Mapping
5 分
A router uses Dijkstra's algorithm to calculate the shortest path from Node A to Node E in a weighted network. The vertices are A, B, C, D, and E. The edge weights are: A - B: 4; A - C: 2; B - C: 1; B - D: 5; C - D: 8; C - E: 10; D - E: 2. Calculate the shortest path from Node A to Node E. Show the step-by-step progress of the algorithm, listing each visited node and the temporary or permanent shortest distances updated during each step. State the final shortest path and its total weight.
查看答案詳解收起答案詳解
解題
Dijkstra's algorithm execution: 1. Initialize distances from A: A=0, B=inf, C=inf, D=inf, E=inf. 2. Visit A (shortest distance = 0): update neighbours: B = 4 (via A), C = 2 (via A). 3. Select unvisited node with smallest distance: C (distance = 2). Visit C: update neighbours: B = min(4, 2 + 1) = 3 (via C); D = 2 + 8 = 10 (via C); E = 2 + 10 = 12 (via C). 4. Select next unvisited node with smallest distance: B (distance = 3). Visit B: update neighbours: D = min(10, 3 + 5) = 8 (via B). 5. Select next unvisited node with smallest distance: D (distance = 8). Visit D: update neighbours: E = min(12, 8 + 2) = 10 (via D). 6. Select final unvisited node: E (distance = 10). Visit E. Shortest path: A -> C -> B -> D -> E. Total weight: 10.
評分準則
1 mark: Shows correct initialization and first step visiting A (C is 2, B is 4). 1 mark: Shows step visiting C and updating B to 3, D to 10, E to 12. 1 mark: Shows step visiting B and updating D to 8. 1 mark: Shows step visiting D and updating E to 10. 1 mark: Identifies correct final shortest path A -> C -> B -> D -> E and correct total weight 10.
題目 8 · Calculation / Mapping
5 分
A hash table has 10 slots (indexed 0 to 9). The hash function used is: \(H(key) = key \pmod{10}\). Collisions are resolved using open addressing with linear probing (with a step size of 1). Show the step-by-step mapping of the following keys as they are inserted into an initially empty hash table in this exact order: 43, 23, 72, 33, 52. For each key, state its initial hash value, any collision details, and its final index. Finally, show the resulting hash table layout.
查看答案詳解收起答案詳解
解題
1. Key 43: \(H(43) = 3\). Slot 3 is empty, so insert 43 at index 3. 2. Key 23: \(H(23) = 3\). Slot 3 is occupied (collision). Probing next slot: index 4 is empty, so insert 23 at index 4. 3. Key 72: \(H(72) = 2\). Slot 2 is empty, so insert 72 at index 2. 4. Key 33: \(H(33) = 3\). Slot 3 is occupied. Probe 4 (occupied). Probe 5 (empty), so insert 33 at index 5. 5. Key 52: \(H(52) = 2\). Slot 2 is occupied. Probe 3 (occupied). Probe 4 (occupied). Probe 5 (occupied). Probe 6 (empty), so insert 52 at index 6. Final Hash Table contents: Index 2: 72; Index 3: 43; Index 4: 23; Index 5: 33; Index 6: 52 (other indexes are empty).
評分準則
1 mark: Inserts 43 at index 3 and 72 at index 2 correctly. 1 mark: Inserts 23 at index 4 with correct description of linear probing (collision at 3). 1 mark: Inserts 33 at index 5 after linear probing from 3 through 4. 1 mark: Inserts 52 at index 6 after linear probing from 2 through 5. 1 mark: Shows correct final state of the entire hash table.
題目 9 · Analytical Explanation
5 分
An 12-bit floating-point representation uses 8 bits for the mantissa and 4 bits for the exponent, both in two's complement.
Explain, using mathematical reasoning and binary representations, why adding a very small positive number such as \(0.015625\) (\(2^{-6}\)) to a large positive number such as \(16.0\) (\(2^{4}\)) results in a "loss of precision", leading to the sum remaining exactly \(16.0\).
查看答案詳解收起答案詳解
解題
1. Express both numbers in normalized binary floating-point form: - \(16.0 = 0.10000000_2 \times 2^5\) (Mantissa: `01000000`, Exponent: `0101` which is \(+5\)) - \(0.015625 = 0.10000000_2 \times 2^{-5}\) (Mantissa: `01000000`, Exponent: `1011` which is \(-5\))
2. Align the exponents to the larger value (\(+5\)): - The difference between exponents is \(5 - (-5) = 10\). - The mantissa of the smaller number must be shifted 10 positions to the right.
3. Apply the shift to the 8-bit mantissa: - Shifting `0.10000000` to the right by 10 places yields `0.00000000` (all original significant bits are lost because the register only holds 8 bits).
4. Perform addition: - \(0.10000000_2 \times 2^5 + 0.00000000_2 \times 2^5 = 0.10000000_2 \times 2^5\) (which is exactly \(16.0\)). Thus, the addition has no effect due to underflow/loss of precision.
評分準則
- 1 mark: Identify the exponents of both numbers when normalized (\(+5\) for \(16.0\) and \(-5\) for \(0.015625\)). - 1 mark: Explain that to perform binary addition, the exponents must be aligned to the larger value (\(+5\)). - 1 mark: Compute the required shift of 10 positions to the right for the smaller number. - 1 mark: Explain that since the mantissa is constrained to 8 bits, shifting right by 10 places causes all significant bits to be discarded (underflow to zero). - 1 mark: Show that adding the zeroed mantissa results in the sum being identical to the original large value (\(16.0\)), completing the analytical proof.
題目 10 · Analytical Explanation
5 分
A router in an IPv4 network receives an IP packet destined for the IP address `192.168.4.75`. The router's routing table contains the following entries:
| Destination Network | Subnet Mask | Next Hop / Interface | | :--- | :--- | :--- | | `192.168.4.0` | `255.255.255.192` | Interface A | | `192.168.4.64` | `255.255.255.224` | Interface B | | `192.168.0.0` | `255.255.0.0` | Interface C | | `0.0.0.0` | `0.0.0.0` | Interface D |
Explain, by showing the binary mathematical operations involved, how the router determines which interface to use to forward the packet.
查看答案詳解收起答案詳解
解題
1. Convert the final octet of the destination IP `192.168.4.75` to binary: `75` is `01001011_2`. 2. Apply bitwise AND with subnet mask `255.255.255.192` (last octet `192` = `11000000_2`): - `01001011` AND `11000000` = `01000000_2` (which is `64`). The destination network is `192.168.4.64`. This does not match `192.168.4.0` (Interface A). 3. Apply bitwise AND with subnet mask `255.255.255.224` (last octet `224` = `11100000_2`): - `01001011` AND `11100000` = `01000000_2` (which is `64`). The destination network is `192.168.4.64`. This matches Interface B. 4. Apply bitwise AND with subnet mask `255.255.0.0`: - The result is `192.168.0.0`, which matches Interface C. 5. Longest Prefix Match resolution: - Interface B uses a mask length of 27 bits (`255.255.255.224`). - Interface C uses a mask length of 16 bits (`255.255.0.0`). - Since 27 > 16, Interface B is chosen as it has the longest matching prefix.
評分準則
- 1 mark: Explain that a bitwise AND operation is performed between the destination IP address and the subnet mask of each entry. - 1 mark: Show the correct binary conversion and AND process for at least one subnet mask (e.g., `01001011` AND `11100000` = `01000000`). - 1 mark: Identify that both the subnet for Interface B (`192.168.4.64`) and Interface C (`192.168.0.0`) match the destination IP. - 1 mark: Explain the 'longest prefix match' (or 'most specific route') routing rule used to resolve conflicts when multiple matches occur. - 1 mark: Conclude that Interface B is selected because `/27` is a longer prefix (more 1s) than `/16`.
題目 11 · Analytical Explanation
5 分
Explain how MIMD (Multiple Instruction, Multiple Data) computer architecture differs from SIMD (Single Instruction, Multiple Data) computer architecture. Your explanation should make reference to the execution of instructions, the processing of data streams, memory architectures, and typical application scenarios.
查看答案詳解收起答案詳解
解題
MIMD and SIMD differ in key architectural areas: - **Instruction Execution**: SIMD employs a single control unit to broadcast a single instruction to all processing units, executing them in lockstep. MIMD has multiple independent processors, each with its own control unit and program counter, executing different instructions asynchronously. - **Data Streams**: SIMD operates on multiple data points simultaneously using one instruction (ideal for parallel vectors). MIMD handles multiple instruction streams operating on multiple data streams. - **Memory Models**: SIMD systems rely on unified, synchronized memory structures. MIMD systems can utilize either shared memory (e.g., SMP systems where processors share RAM) or distributed memory (e.g., clusters where processors communicate via interconnect messages). - **Handling Branches**: SIMD is inefficient at handling conditional branches because execution branches must be serialized. MIMD handles branching natively with zero performance impact on other processors. - **Applications**: SIMD is used in graphics cards (GPUs), vector math, and image processing. MIMD is used in multi-core general-purpose CPUs and supercomputing clusters.
評分準則
- 1 mark: Contrast instruction execution (SIMD is lock-step/single control unit; MIMD has multiple independent control units/asynchronous execution). - 1 mark: Contrast data streams (SIMD applies one operation to multiple data elements; MIMD applies multiple operations on multiple distinct data sets). - 1 mark: Contrast memory architectures (SIMD relies on highly synchronized shared memory; MIMD can use shared memory or distributed memory architectures with message passing). - 1 mark: Explain how branching/conditional code affects performance (SIMD degrades due to path serialization; MIMD handles independent branches natively without performance loss). - 1 mark: Provide valid application examples for both (e.g., SIMD: GPUs/image processing; MIMD: multi-core general CPUs/distributed high-performance clusters).
題目 12 · Analytical Explanation
5 分
Explain the process of how a client's web browser verifies the authenticity of a web server’s digital certificate during the establishment of a secure HTTPS connection using SSL/TLS.
查看答案詳解收起答案詳解
解題
During the SSL/TLS handshake, the client browser performs the following verification steps on the server's certificate: 1. **CA Public Key Retrieval**: The browser reads the identity of the certificate's issuer (the CA) and retrieves that CA's public key from its pre-installed, trusted root certificate store. 2. **Signature Decryption**: The browser decrypts the digital signature attached to the certificate using the CA's public key. Since the signature was encrypted with the CA's private key, successful decryption proves the certificate's authenticity. 3. **Integrity Check**: The browser applies the designated cryptographic hashing algorithm (e.g., SHA-256) to the plaintext fields of the certificate. It compares this calculated hash to the decrypted hash from the digital signature. If they match, the certificate has not been altered. 4. **Domain and Expiry Validation**: The browser verifies that the domain name in the certificate matches the domain name of the accessed website and check that the current date falls within the certificate's validity period. 5. **Revocation Check**: The browser contacts the CA or checks a Certificate Revocation List (CRL) or uses OCSP (Online Certificate Status Protocol) to confirm the certificate has not been revoked.
評分準則
- 1 mark: State that the browser retrieves the issuing CA's public key from its built-in trusted root store. - 1 mark: Explain that the browser uses the CA's public key to decrypt the digital signature (proving authenticity because only the CA has the private key). - 1 mark: Explain the integrity check (calculating a hash of the certificate and comparing it to the decrypted signature hash to ensure no tampering occurred). - 1 mark: Identify domain matching checks (checking Common Name/SAN against the requested URL) and validity period checks. - 1 mark: Describe revocation checking using CRLs or OCSP to ensure the certificate remains active and has not been revoked.
The following functional dependencies exist: - `ProjectID` \(\rightarrow\) `ProjectName` - `EmployeeID` \(\rightarrow\) `EmployeeName` - `(ProjectID, EmployeeID)` \(\rightarrow\) `HoursWorked`
Analyze the normalization state of this table. Explain why it is not in Third Normal Form (3NF), and describe the steps required to convert this table into a set of tables that satisfy 3NF.
查看答案詳解收起答案詳解
解題
1. **Identify Primary Key**: The primary key for the unnormalized table must be the composite key `(ProjectID, EmployeeID)` because only both values together can uniquely determine `HoursWorked`. 2. **Analyze 2NF Violation**: A table is in Second Normal Form (2NF) if it contains no partial dependencies. In this table, `ProjectName` depends solely on `ProjectID`, and `EmployeeName` depends solely on `EmployeeID`. Because these non-key attributes depend on only parts of the composite primary key, this is a partial dependency violation. It is not in 2NF, which means it cannot be in 3NF. 3. **Decomposition to achieve 3NF**: - Create a `Project` table with primary key `ProjectID`: `Project(ProjectID, ProjectName)` - Create an `Employee` table with primary key `EmployeeID`: `Employee(EmployeeID, EmployeeName)` - Create a bridging/assignment table with composite key `(ProjectID, EmployeeID)`: `ProjectAssignment(ProjectID, EmployeeID, HoursWorked)` (where `ProjectID` and `EmployeeID` act as foreign keys). These three tables now possess only full functional dependencies on their primary keys and no transitive dependencies, satisfying 3NF.
評分準則
- 1 mark: State that the primary key of the initial table is the composite key `(ProjectID, EmployeeID)`. - 1 mark: Define the 2NF violation by explaining the partial dependencies (`ProjectName` depends only on `ProjectID`; `EmployeeName` depends only on `EmployeeID`). - 1 mark: Explain that 3NF requires the table to first be in 2NF (meaning all partial dependencies must be removed) and have no transitive dependencies. - 1 mark: Specify the correct decomposed tables for entities: `Project(ProjectID, ProjectName)` and `Employee(EmployeeID, EmployeeName)` with their respective primary keys. - 1 mark: Specify the correct link table `ProjectAssignment(ProjectID, EmployeeID, HoursWorked)` with foreign key constraints and the fully-dependent non-key attribute.
題目 14 · Analytical Explanation
5 分
In an 12-bit floating-point format, the mantissa is 8 bits and the exponent is 4 bits. Both are stored using two's complement.
State the normalized 12-bit binary representation of the minimum (most negative) non-zero real value that can be represented. Show your working by explaining the state of the sign bit, the pattern of the remaining mantissa bits, and the chosen exponent.
查看答案詳解收起答案詳解
解題
1. **Normalized Negative Mantissa**: A normalized negative number in two's complement mantissa must start with the bits `10...` to represent a value in the range \([-1.0, -0.5)\). 2. **Most Negative Mantissa Value**: The lowest possible value represented by an 8-bit normalized mantissa is exactly \(-1.0\), which corresponds to the binary string `10000000`. 3. **Choosing the Exponent**: To obtain the most negative overall value, we must multiply our negative mantissa by the largest possible positive factor. This requires the largest possible exponent. 4. **Largest Exponent**: The exponent is a 4-bit two's complement integer. The range of a 4-bit two's complement number is \([-8, +7]\). The maximum positive exponent is \(+7\), which is represented in binary as `0111`. 5. **Combining the Bit Patterns**: Joining the 8-bit mantissa (`10000000`) and the 4-bit exponent (`0111`) yields the 12-bit string: `100000000111` (which represents \(-1.0 \times 2^7 = -128.0\)).
評分準則
- 1 mark: State that a normalized negative mantissa must start with binary bits `1` and `0` (range \([-1.0, -0.5)\)). - 1 mark: Identify that the most negative mantissa value is \(-1.0\), represented in binary as `10000000`. - 1 mark: Explain that to find the most negative value overall, the largest positive exponent is required to maximize magnitude. - 1 mark: Identify the maximum positive exponent in 4-bit two's complement as \(+7\), represented as binary `0111`. - 1 mark: Combine these components to give the correct 12-bit string `100000000111` (or calculate the correct decimal equivalent of \(-128.0\)).
題目 15 · Analytical Explanation
5 分
Compare packet switching and circuit switching network technologies. Explain why packet switching is highly efficient for general internet traffic (which is bursty in nature), but can result in performance degradation (such as jitter and latency) for real-time applications like VoIP (Voice over IP) compared to circuit switching.
查看答案詳解收起答案詳解
解題
- **Resource Allocation**: Circuit switching establishes a dedicated physical channel for the duration of a session. Packet switching breaks data into packets that travel independently, sharing transmission lines. - **Efficiency under Bursty Traffic**: Internet traffic consists of active bursts and idle silences. In circuit switching, idle gaps waste reserved bandwidth. Packet switching dynamically multiplexes packets from different sources across the same links, maximizing link utilization. - **Performance Degradation (Jitter and Latency)**: In packet switching, packets experience queuing delays at routers and can take different paths. This produces variable delay (jitter) and delivery delays (latency). If packets arrive late or out of order, VoIP audio becomes garbled or broken. - **Circuit Switching Advantage for Real-time**: Circuit switching provides a fixed, guaranteed route with zero jitter and constant latency, ensuring high performance for real-time audio streams, despite the initial overhead of line setup and bandwidth inefficiency.
評分準則
- 1 mark: Contrast resource allocation (circuit switching uses a dedicated, reserved circuit; packet switching shares physical paths dynamically using packets). - 1 mark: Explain why packet switching is efficient for bursty traffic (multiplexes data, allowing other users to use the line during idle periods). - 1 mark: Explain why circuit switching is inefficient for bursty traffic (reserved line sits idle, wasting network capacity during silences). - 1 mark: Detail how packet switching introduces latency and jitter (variable routing paths, router queuing delays, and out-of-order delivery). - 1 mark: Relate these issues to real-time applications like VoIP (which require consistent, timely, sequential delivery of data packets to avoid sound dropouts, making circuit switching's guaranteed constant latency preferable).
Paper 41 (Practical Skills)
Develop and test code in Java, Python, or Visual Basic.
12 題目 · 76 分
題目 1 · practical
7 分
An array `Stock` of 100 elements contains records of type `Product`. Each record has two attributes: `ProductID` (integer) and `Quantity` (integer). The array is sorted in ascending order of `ProductID`.
Write Python code for a function `BinarySearch(Stock, SearchID)` that uses a binary search algorithm to search for a product with a `ProductID` matching `SearchID`.
The function must: - Return the array index of the matching product if found. - Return -1 if the product is not found.
查看答案詳解收起答案詳解
解題
The binary search algorithm starts with two pointers representing the search space: `low` at 0 and `high` at the last index of the array (99, or `len(Stock) - 1`). In each iteration of the `while` loop, the midpoint index `mid` is calculated using integer division (`//`). The `ProductID` attribute of the product at `mid` is compared with the target `SearchID`. If they match, `mid` is returned. If the ID at `mid` is less than the search value, the lower boundary `low` is updated to `mid + 1` to search the right half. Otherwise, the upper boundary `high` is updated to `mid - 1` to search the left half. If the loop terminates because `low` exceeds `high`, the target is not present, and `-1` is returned.
評分準則
1 mark: Correct function header with parameters `Stock` and `SearchID`. 1 mark: Initializing search boundaries: `low` to 0 and `high` to last index. 1 mark: Loop with condition `low <= high` (or equivalent structure). 1 mark: Calculating the midpoint index correctly using integer division. 1 mark: Correctly accessing the attribute `ProductID` from the `Stock` array element. 1 mark: Updating boundaries: setting `low = mid + 1` and `high = mid - 1` based on the comparison. 1 mark: Returning the index when found and returning -1 when the loop finishes without finding the value.
題目 2 · practical
7 分
Write Python code for a procedure `BubbleSortDesc(DataArray)` to sort a 1-dimensional array of integers named `DataArray` into descending order using an optimized bubble sort algorithm.
The algorithm must use a boolean flag to track whether any swaps occurred during a pass, terminating early if the array becomes fully sorted before all passes are complete.
查看答案詳解收起答案詳解
解題
An optimized bubble sort uses nested loops. The outer loop controls the passes, while the inner loop compares adjacent elements. In this descending sort, if the current element is less than the adjacent element (`DataArray[j] < DataArray[j+1]`), they are swapped. A boolean variable `swapped` is initialized to `False` at the beginning of each pass of the outer loop. If a swap occurs, `swapped` is set to `True`. At the end of the inner loop, if `swapped` is still `False`, it means the array is already sorted, and the outer loop is terminated prematurely using a `break` statement.
評分準則
1 mark: Correct function header with parameter `DataArray`. 1 mark: Outer loop iterating up to `n - 1` times. 1 mark: Inner loop comparing adjacent elements, stopping short of already sorted items (e.g., using `n - i - 1`). 1 mark: Comparison check for descending order (`DataArray[j] < DataArray[j+1]`). 1 mark: Correctly swapping elements using a temporary variable or tuple assignment. 1 mark: Initializing a boolean flag to `False` before each pass and setting it to `True` upon a swap. 1 mark: Checking the flag and exiting the outer loop early if no swaps occurred.
題目 3 · practical
7 分
An array `Usernames` contains 10 elements of type string.
Write Python code for a procedure `InsertionSortAsc(Usernames)` that sorts the elements in alphabetical order (ascending order) using the Insertion Sort algorithm.
查看答案詳解收起答案詳解
解題
The insertion sort algorithm begins at the second element (index 1) and treats it as the `key`. The inner loop shifts elements of the sorted sublist (`Usernames[0..i-1]`) that are greater than the `key` to the right by one position. The inner loop terminates either when the start of the list is reached (`j < 0`) or an element smaller than or equal to the `key` is found. Finally, the `key` is inserted into its correct position at index `j + 1`.
評分準則
1 mark: Correct procedure header with parameter. 1 mark: Outer loop iterating from index 1 to the end of the array. 1 mark: Storing the current element in a temporary `key` variable. 1 mark: Correctly initializing the inner pointer variable `j = i - 1`. 1 mark: Inner loop condition checking bounds (`j >= 0`) and key comparison (`Usernames[j] > key` for ascending). 1 mark: Shifting the larger elements one index to the right inside the loop. 1 mark: Correctly inserting the `key` value at position `j + 1` after the inner loop terminates.
題目 4 · practical
7 分
A 2-dimensional array named `Grid` of dimensions 10 rows by 10 columns contains integer values.
Write Python code for a function `SearchGrid(Grid, TargetValue)` that performs a linear search across the entire 2D array to find the location of `TargetValue`.
The function must: - Return a tuple `(row, col)` representing the coordinates of the first occurrence of `TargetValue`. - Return the tuple `(-1, -1)` if the value is not present in the grid.
查看答案詳解收起答案詳解
解題
A linear search in a 2D array requires examining each element row by row (or column by column). We use nested loops to iterate through every cell in the grid. The outer loop iterates through the row indices from 0 to 9, and the inner loop iterates through the column indices from 0 to 9. We check if `Grid[row][col]` matches `TargetValue`. If a match is found, we immediately return the coordinates as `(row, col)`. If both loops complete and the value was not found, the function returns `(-1, -1)`.
評分準則
1 mark: Correct function header with parameters `Grid` and `TargetValue`. 1 mark: Outer loop to iterate through all 10 row indices. 1 mark: Inner loop to iterate through all 10 column indices. 1 mark: Correct indexing syntax for a 2D array: `Grid[row][col]`. 1 mark: Comparison of the array cell against `TargetValue`. 1 mark: Immediately returning `(row, col)` upon finding a match. 1 mark: Returning `(-1, -1)` after both loops exhaustively finish without finding a match.
題目 5 · practical
6 分
Write Python code to define a base class `MediaItem` and its subclass `Book`.
The class `MediaItem` must have: - Private attributes: `__Title` (string) and `__RunTime` (integer, representing minutes) - A constructor that accepts title and runtime parameters and initialises the private attributes. - Getter methods: `GetTitle()` and `GetRunTime()` that return the respective values.
The subclass `Book` must inherit from `MediaItem` and have: - An additional private attribute: `__Author` (string) - A constructor that accepts parameters for title, runtime, and author, and correctly initialises all three (calling the base class constructor where appropriate). - A method `GetDetails()` that returns a string formatted as: '[Title] by [Author] (Runtime: [RunTime] mins)' where [Title], [Author], and [RunTime] are replaced with their respective values.
查看答案詳解收起答案詳解
解題
To implement inheritance in Python, define the class MediaItem with a constructor setting its private variables (using double leading underscores). Write public getter methods to allow child classes or external objects to access these values. Next, define Book with MediaItem passed in parentheses to declare inheritance. Inside the Book constructor, use super().__init__(...) to initialize the parent's attributes, then set __Author. The GetDetails() method retrieves parent properties using getter methods and builds the formatted string.
評分準則
1 mark: Define class MediaItem with constructor and private attributes __Title and __RunTime. 1 mark: Implement public getters GetTitle() and GetRunTime(). 1 mark: Define class Book inheriting from MediaItem with private attribute __Author. 1 mark: Implement Book constructor taking three parameters. 1 mark: Call parent class constructor using super().__init__(title, runtime). 1 mark: Implement GetDetails() calling GetTitle() and GetRunTime() and formatting output string correctly.
題目 6 · practical
6 分
Write Python code to implement class composition.
Define a class `Customer` with: - Private attributes: `__CustomerName` (string), `__Email` (string) - A constructor to initialise these attributes. - Public getter methods: `GetName()` and `GetEmail()`.
Define a class `Booking` with: - Private attributes: `__BookingID` (string), `__Client` (an instance of the `Customer` class) - A constructor that takes a booking ID and a `Customer` object as parameters and initialises the private attributes. - A method `GetBookingSummary()` that returns a string containing the booking ID and the customer's name, formatted as: 'Booking ID: [BookingID], Customer: [CustomerName]'.
查看答案詳解收起答案詳解
解題
In this composite relationship, a Booking object stores a reference to a Customer object in its private field __Client. Since __CustomerName is private within Customer, Booking cannot access it directly. Thus, Customer must provide the public getter GetName() which Booking calls within GetBookingSummary().
評分準則
1 mark: Define Customer class with constructor initialising private attributes. 1 mark: Implement public getters GetName() and GetEmail() in Customer. 1 mark: Define Booking class with constructor taking bookingID and client. 1 mark: Correctly assign client parameter (representing Customer object) to private attribute __Client. 1 mark: Implement GetBookingSummary() method in Booking. 1 mark: Retrieve customer name inside GetBookingSummary() by calling GetName() on the __Client reference and return correctly formatted string.
題目 7 · practical
6 分
Write Python code to implement polymorphism.
Define a base class `Appliance` with: - Private attributes: `__Brand` (string), `__PowerRating` (integer, in watts) - A constructor to initialise these attributes. - A getter method `GetPower()` that returns the power rating. - A method `CalculatePower(hours)` that calculates and returns the electrical energy consumed as the product of power rating and hours (i.e., `__PowerRating * hours`).
Define a subclass `SmartAppliance` that inherits from `Appliance` and overrides `CalculatePower`: - It has an additional private attribute: `__EfficiencyFactor` (float) - A constructor that initialises brand, power rating, and efficiency factor, calling the base class constructor. - An overridden method `CalculatePower(hours)` that overrides the parent's method and returns the energy consumption adjusted by the efficiency factor: `power rating * hours * efficiency factor`.
查看答案詳解收起答案詳解
解題
Polymorphism allows a subclass to override a method in the superclass with its own specialized implementation. Since __PowerRating is private in Appliance, SmartAppliance must use self.GetPower() to retrieve the rating value before performing the custom calculation.
評分準則
1 mark: Define base class Appliance with constructor and private attributes. 1 mark: Implement getter method GetPower() returning __PowerRating. 1 mark: Implement CalculatePower(hours) in Appliance returning power * hours. 1 mark: Define subclass SmartAppliance inheriting from Appliance. 1 mark: Correctly call parent constructor using super().__init__(brand, powerRating) and assign private attribute __EfficiencyFactor. 1 mark: Override CalculatePower(hours) in SmartAppliance correctly accessing base power via self.GetPower() and incorporating __EfficiencyFactor.
題目 8 · practical
6 分
Write Python code to implement a class `BankAccount` with validation.
The class `BankAccount` must have: - Private attributes: `__AccountNumber` (string), `__Balance` (float, representing money) - A constructor that takes an account number as a parameter, initialises `__AccountNumber` to this value, and initialises `__Balance` to `0.0`. - A method `Deposit(amount)`: - If `amount` is greater than `0`, adds `amount` to `__Balance` and returns `True`. - Otherwise, makes no change and returns `False`. - A method `Withdraw(amount)`: - If `amount` is greater than `0` AND `__Balance` is greater than or equal to `amount`, subtracts `amount` from `__Balance` and returns `True`. - Otherwise, makes no change and returns `False`. - A getter method `GetBalance()` that returns the current value of `__Balance`.
查看答案詳解收起答案詳解
解題
This scenario models encapsulation and robustness in object state. The state parameter __Balance can only be updated via the verified public methods Deposit and Withdraw. Conditions ensure negative values or excessive withdrawals are blocked.
評分準則
1 mark: Correct class header and constructor initialising __AccountNumber to the parameter and __Balance to 0.0. 1 mark: Implement Deposit method checking if amount > 0. 1 mark: Correctly add amount to balance and return True (otherwise returning False) in Deposit. 1 mark: Implement Withdraw method checking both conditions (amount > 0 and __Balance >= amount). 1 mark: Correctly subtract amount from balance and return True (otherwise returning False) in Withdraw. 1 mark: Implement getter GetBalance() returning __Balance.
題目 9 · practical
6 分
A fleet management system tracks vehicles using OOP.
Write Python code to define two classes, `Vehicle` and `Fleet`.
The class `Vehicle` has: - Private attributes: `__RegNo` (string), `__Mileage` (integer) - A constructor to initialise these attributes. - A public getter method `GetRegNo()` that returns the registration number.
The class `Fleet` has: - Private attributes: `__FleetList` (a list/array to hold up to 10 objects of class `Vehicle`), `__Count` (integer, storing the current number of vehicles) - A constructor that initialises `__FleetList` as an empty list and `__Count` to `0`. - A method `AddVehicle(newVehicle)`: - If the fleet is not full (i.e., `__Count` is less than 10), it appends `newVehicle` to `__FleetList`, increments `__Count` by 1, and returns `True`. - Otherwise, it returns `False`. - A method `FindVehicle(reg)`: - It searches through the list up to the number of stored elements (`__Count`). - If a vehicle with a registration number matching the parameter `reg` is found, it returns its index in the list. - If it is not found, it returns `-1`.
查看答案詳解收起答案詳解
解題
The Fleet class manages an aggregation of Vehicle instances. Inside the Fleet constructor, an empty list __FleetList is initialized. AddVehicle checks if __Count < 10 before appending and incrementing. FindVehicle iterates through the existing vehicles in __FleetList using range(__Count), calls GetRegNo() on each vehicle object, compares it to the target parameter reg, and returns the appropriate index or -1 if not found.
評分準則
1 mark: Define Vehicle class with constructor and GetRegNo() getter. 1 mark: Define Fleet class with constructor setting __FleetList to empty list and __Count to 0. 1 mark: Implement AddVehicle(newVehicle) checking if __Count < 10. 1 mark: In AddVehicle, append object to list, increment count, and return True (or False if full). 1 mark: Implement search in FindVehicle(reg) iterating up to __Count (or length of list). 1 mark: Access each vehicle's registration via GetRegNo() inside FindVehicle, compare with parameter reg, return index if found, else return -1.
題目 10 · practical
6 分
A programmer is implementing a Circular Queue as an Abstract Data Type (ADT) in Python. The queue is stored in a 1D array named QueueArray with 5 elements (indices 0 to 4).
The implementation uses three global variables: - HeadPointer (initialized to -1) - TailPointer (initialized to -1) - NumItems (initialized to 0)
Write Python code for the procedure Enqueue(NewItem) that adds a new item to the queue. The procedure must check if the queue is full and output an error message if so. Otherwise, it must update the pointers, insert the item, and increment the item count.
查看答案詳解收起答案詳解
解題
The procedure first checks if the queue is full by comparing NumItems with the maximum capacity of 5. If it is full, an appropriate error message is displayed. Otherwise, if the queue is currently empty (indicated by HeadPointer being -1), HeadPointer is initialized to 0. The TailPointer is then updated circularly using modulo 5 arithmetic: TailPointer = (TailPointer + 1) % 5. Finally, the new item is stored in QueueArray at the updated TailPointer index, and NumItems is incremented by 1.
評分準則
1 mark: Correctly check if the queue is full (NumItems == 5) and output an error message. 1 mark: Check if the queue is empty (HeadPointer == -1) and set HeadPointer to 0. 1 mark: Correctly calculate the circular update for TailPointer using modulo or equivalent logic. 1 mark: Assign NewItem to the QueueArray at index TailPointer. 1 mark: Increment NumItems by 1. 1 mark: Declare global scope for pointers/variables and write correct Python syntax.
題目 11 · practical
6 分
A Stack ADT is implemented using a 1D array named StackArray with 10 elements (indices 0 to 9). The global integer variable TopPointer points to the top element of the stack and is initialized to -1.
Write Python code for a function Pop() that removes and returns the element at the top of the stack. The function must handle stack underflow by outputting an error message and returning -1 if the stack is empty.
查看答案詳解收起答案詳解
解題
The Pop function must first handle stack underflow by checking if TopPointer is -1. If it is, the function prints an error message and returns -1. If elements exist, it retrieves the item stored at StackArray[TopPointer], decrements TopPointer by 1, and returns the retrieved item.
評分準則
1 mark: Check for empty stack condition (TopPointer == -1). 1 mark: Correctly output an underflow error message when empty. 1 mark: Return -1 when stack underflow occurs. 1 mark: Retrieve and store the value from StackArray at TopPointer. 1 mark: Decrement TopPointer by 1. 1 mark: Return the popped value from the non-empty path.
題目 12 · practical
6 分
A Binary Search Tree (BST) is implemented using a 1D array of node records. The node structure is defined as follows:
The tree array is named BSTArray and has a root pointer named RootPointer.
Write a recursive Python function SearchBST(CurrentNodePointer, SearchValue) that searches for a specific value in the binary search tree. The function must return the index pointer of the node if the value is found, or -1 if the value is not in the tree.
查看答案詳解收起答案詳解
解題
The function uses recursion to traverse the binary search tree. There are two base cases: 1. If CurrentNodePointer is -1, the tree or subtree is empty, meaning the value does not exist, so the function returns -1. 2. If the current node's data matches SearchValue, the search is successful, and the function returns the CurrentNodePointer.
For the recursive step: - If SearchValue is less than the current node's data, the function calls itself with the left child's pointer. - If SearchValue is greater, it calls itself with the right child's pointer.
評分準則
1 mark: Base case checking if pointer is -1 and returning -1. 1 mark: Base case checking if data equals search value and returning current pointer. 1 mark: Comparison check if SearchValue is less than current node data. 1 mark: Recursive call using LeftPointer with matching return. 1 mark: Recursive call using RightPointer with matching return. 1 mark: Correct function header and parameters matching recursive calls.
想知道自己有幾分把握?
Thinka 是 DSE 學生用的 AI 練習應用程式,有無限量練習題、即時自動批改和詳細解題步驟。逾 100,000 名學生用它確認自己真的識,而不只是「以為識」。