An original Thinka practice paper modelled on the structure and difficulty of the Jun 2024 Cambridge OCR A Level Computer Science - H446 paper. Not affiliated with or reproduced from Cambridge.
卷一 甲部 (H446/01)
Answer all questions. Calculators are not allowed. Quality of extended response is assessed on asterisked questions.
33 題目 · 114 分
題目 1 · short_answer
2 分
Explain the relationship between the Program Counter (PC) and the Memory Address Register (MAR) during the fetch stage of the Fetch-Decode-Execute cycle.
查看答案詳解收起答案詳解
解題
At the start of the fetch stage, the CPU needs to locate the next instruction. The Program Counter (PC) stores the memory address of this next instruction. This address is copied from the PC to the Memory Address Register (MAR) via the address bus so that the control unit can locate and read the instruction from main memory.
評分準則
1 mark for stating that the PC holds the address of the next instruction to be fetched. 1 mark for stating that this address is copied directly into the MAR to locate the instruction.
題目 2 · short_answer
2 分
State two advantages of using asymmetric encryption over symmetric encryption when establishing a secure connection to a web server.
查看答案詳解收起答案詳解
解題
1. Key Exchange: Asymmetric encryption uses public and private keys, meaning a shared secret key does not need to be sent over an insecure connection, preventing interception. 2. Authentication: The digital certificate containing the server's public key is verified by a trusted authority, confirming the server's identity to the client.
評分準則
1 mark for explaining that no shared secret key needs to be exchanged (avoids key distribution risks). 1 mark for explaining that it allows authentication of the server (using digital certificates/signatures).
題目 3 · short_answer
2 分
Explain how a collision occurs in a hash table, and describe one method used to resolve this collision.
查看答案詳解收起答案詳解
解題
A collision occurs when a hashing algorithm calculates the exact same array index for two completely different input keys. One resolution method is linear probing (open addressing), where the algorithm searches sequentially for the next available slot in the table. Another method is chaining (closed addressing), where each index contains a pointer to a linked list of records that share the same hash value.
評分準則
1 mark for explaining that a collision is when two different input keys produce the same hash value/index. 1 mark for describing a valid resolution method: either linear probing (searching for the next free slot) or chaining (creating a linked list at that index).
題目 4 · short_answer
2 分
Define the term 'referential integrity' in a relational database, and explain how it is enforced.
查看答案詳解收起答案詳解
解題
Referential integrity is a state of consistency where every foreign key value in a table matches an existing, valid primary key value in the related table. This prevents orphan records. It is enforced automatically by the Database Management System (DBMS) using foreign key constraints, which reject operations that break the link (like deleting a parent record still referenced by a child).
評分準則
1 mark for defining referential integrity (ensuring foreign keys point to valid primary keys / no orphaned records). 1 mark for explaining that it is enforced by DBMS foreign key constraints (e.g., cascading deletes or blocking invalid inserts).
題目 5 · short_answer
2 分
State two advantages of normalizing a floating-point binary number.
查看答案詳解收起答案詳解
解題
1. Maximises precision: By ensuring that there are no leading unnecessary zeros or ones in the mantissa, the available bits are used as efficiently as possible for representing the actual value. 2. Unique representation: It ensures there is only one way to represent any real number, making arithmetic comparisons much faster and simpler.
評分準則
1 mark for: Maximizes the precision/accuracy of the represented value within the allocated bits. 1 mark for: Ensures a unique representation of each number (simplifying comparisons and calculations).
題目 6 · short_answer
2 分
State the purpose of a device driver and explain why it is necessary.
查看答案詳解收起答案詳解
解題
A device driver is a utility program that translates generic operating system commands into specific hardware instructions. It is necessary because computer hardware is manufactured by many different companies with unique interfaces; the driver allows the OS to support new peripherals without having to rewrite its own code.
評分準則
1 mark for stating that it translates/interfaces between the OS and the physical hardware. 1 mark for explaining that it is necessary to abstract hardware details from the OS, enabling generic OS commands to work on diverse physical models.
題目 7 · short_answer
2 分
Explain the purpose of the Domain Name System (DNS) and how it handles a request if the domain name is not found in the local cache.
查看答案詳解收起答案詳解
解題
The purpose of DNS is to map human-readable domain names (like google.com) to machine-readable IP addresses. If the IP address is not cached locally, the resolver contacts a DNS root server, which directs it to a Top-Level Domain (TLD) server, and finally to an authoritative name server that returns the definitive IP address.
評分準則
1 mark for: Translating human-friendly domain names to IP addresses. 1 mark for: Querying external name servers (e.g., root, TLD, or authoritative servers) to resolve the mapping when not cached.
題目 8 · short_answer
2 分
Simplify the Boolean expression \(\neg(A \lor (B \land \neg C))\) using De Morgan's Laws. Show your working.
查看答案詳解收起答案詳解
解題
First, apply De Morgan's Law to the outermost expression: \(\neg A \land \neg(B \land \neg C)\). Next, apply De Morgan's Law to the right-hand bracketed expression: \(\neg A \land (\neg B \lor \neg\neg C)\). Finally, simplify the double negation of C to get the final expression: \(\neg A \land (\neg B \lor C)\).
評分準則
1 mark for correct intermediate application of De Morgan: \(\neg A \land \neg(B \land \neg C)\). 1 mark for the final simplified Boolean expression: \(\neg A \land (\neg B \lor C)\).
題目 9 · short_answer
2 分
State two roles of the Program Counter (PC) during the Fetch-Decode-Execute cycle.
查看答案詳解收起答案詳解
解題
During the Fetch phase, the Program Counter (PC) stores the address of the next instruction. This address is copied to the Memory Address Register (MAR) via the address bus. Once this has occurred, the PC is incremented so that it points to the subsequent instruction in sequence.
評分準則
1 mark for: Holds the memory address of the next instruction to be fetched. 1 mark for: It is incremented to point to the next instruction.
題目 10 · short_answer
2 分
Describe one key difference between paging and segmentation as memory management techniques.
查看答案詳解收起答案詳解
解題
Paging is a physical division of memory where blocks (pages) are always of the same size. Segmentation is a logical division where memory is divided into segments of differing sizes that correspond to logical units of code (such as subroutines or objects).
評分準則
1 mark for identifying that paging uses fixed-size/physical divisions. 1 mark for identifying that segmentation uses variable-size/logical divisions.
題目 11 · short_answer
2 分
State two benefits of packet switching over circuit switching for transmitting data across a network.
查看答案詳解收起答案詳解
解題
Packet switching does not require a dedicated physical channel, meaning bandwidth can be shared among multiple users, which is highly efficient. Furthermore, if a node or path fails, routers can dynamically redirect packets through alternative paths, preventing data loss and communication dropouts.
評分準則
1 mark for: More efficient use of bandwidth (no idle channels/can share links). 1 mark for: More resilient to network failure (packets can take alternative routes).
題目 12 · short_answer
2 分
Explain the importance of referential integrity in a relational database.
查看答案詳解收起答案詳解
解題
Referential integrity maintains database consistency and accuracy. It ensures that any foreign key in one table must match an existing primary key in the related table. This prevents dangling references, such as having an order for a customer ID that does not exist in the customer table.
評分準則
1 mark for: Ensures database consistency/prevents orphaned or dangling records. 1 mark for: Explaining that a foreign key must correspond to a valid, existing primary key in the related table.
題目 13 · short_answer
2 分
Explain two reasons why two's complement is preferred over sign and magnitude representation for storing negative integers.
查看答案詳解收起答案詳解
解題
Sign and magnitude has two representations for zero (positive and negative), which wastes memory and complicates comparison. Two's complement has a single representation for zero. Additionally, two's complement allows addition and subtraction to be performed using the same hardware circuit, simplifying CPU design.
評分準則
1 mark for: Standard addition circuitry can be used for subtraction (no separate subtraction hardware needed). 1 mark for: Only a single representation of zero (eliminates negative zero, simplifying comparisons).
題目 14 · short_answer
2 分
Explain why asymmetric encryption is preferred over symmetric encryption when securely sharing confidential data over the internet.
查看答案詳解收起答案詳解
解題
In symmetric encryption, a single private key must be shared beforehand. If intercepted during transmission, the security is compromised. Asymmetric encryption uses a public key to encrypt, which can be shared freely, while only the recipient holds the matching private key required to decrypt it, which never needs to be shared.
評分準則
1 mark for: In symmetric encryption, sharing the key across the network introduces interception risks. 1 mark for: Asymmetric encryption uses public/private key pairs so the decryption key is never transmitted.
題目 15 · short_answer
2 分
State two powers given to authorized authorities under the Regulation of Investigatory Powers Act (RIPA).
查看答案詳解收起答案詳解
解題
RIPA regulates the powers of public bodies to carry out surveillance and investigation. Two of its primary powers include demanding ISPs to provide access to digital communications and forcing individuals to decrypt encrypted files or hand over cryptographic keys.
評分準則
1 mark for: Power to intercept and monitor digital communications (such as emails or internet traffic). 1 mark for: Power to demand that encrypted data is decrypted or that decryption keys are surrendered.
題目 16 · short_answer
2 分
Simplify the Boolean expression \(\neg(A \land \neg B)\) using De Morgan's laws and state your final simplified expression.
查看答案詳解收起答案詳解
解題
Using De Morgan's Law, \(\neg(P \land Q)\) is equivalent to \(\neg P \lor \neg Q\). Applying this to \(\neg(A \land \neg B)\) yields \(\neg A \lor \neg(\neg B)\). Since the double negation \(\neg(\neg B)\) simplifies to \(B\), the final expression is \(\neg A \lor B\).
評分準則
1 mark for applying De Morgan's Law to split the expression: \(\neg A \lor \neg(\neg B)\). 1 mark for the final simplified answer: \(\neg A \lor B\).
題目 17 · short_answer
2 分
Explain the role of the Program Counter (PC) during the Fetch stage of the Fetch-Decode-Execute cycle.
查看答案詳解收起答案詳解
解題
1. The PC holds the memory address of the next instruction to be fetched. 2. Once this address is copied to the MAR (Memory Address Register), the PC is incremented to point to the subsequent instruction in memory.
評分準則
1 mark for: Stating that the PC holds the address of the next instruction to be fetched. 1 mark for: Stating that the PC is incremented (by 1) once the address is copied to the MAR (or to point to the subsequent instruction).
題目 18 · short_answer
2 分
Explain how asymmetric encryption differs from symmetric encryption.
查看答案詳解收起答案詳解
解題
Symmetric encryption relies on a single shared key to perform both the encryption and decryption of data. Asymmetric encryption utilizes a mathematically linked key pair: a public key (distributed openly) is used to encrypt the data, and a private key (kept secret by the recipient) is used to decrypt it.
評分準則
1 mark for: Stating that symmetric encryption uses a single/same key for both encryption and decryption. 1 mark for: Stating that asymmetric encryption uses a key pair (public and private keys) where one key encrypts and the other decrypts.
題目 19 · structured_theory
4 分
Describe how pipelining improves processor performance and state two circumstances that can prevent pipelining from operating at maximum efficiency.
查看答案詳解收起答案詳解
解題
Pipelining is a technique where the CPU parallelises the processing of instructions. While one instruction is being executed, the next is being decoded, and the one after that is being fetched. This maximizes the utilization of different parts of the processor, theoretically completing one instruction per clock cycle instead of waiting for a single instruction to go through all three stages before starting the next. However, pipelining efficiency is reduced by: 1. Branching (conditional jumps): If a branch is taken, instructions fetched speculatively into the pipeline must be discarded (flushed). 2. Data dependencies: An instruction cannot proceed if it relies on a register value that has not yet been written back by a preceding instruction.
評分準則
1 mark: Explain that pipelining overlaps the stages of the instruction cycle (Fetch, Decode, Execute) for multiple instructions. 1 mark: Explain that this improves performance by increasing instruction throughput / completing more instructions per unit of time. 1 mark: State 'branching / jump instructions' as a limiting factor (as it requires flushing the pipeline). 1 mark: State 'data dependencies' (or 'resource conflict/interrupts/cache misses') as a limiting factor.
題目 20 · structured_theory
4 分
An operating system uses virtual memory. Compare paging and segmentation, identifying two key differences and two similarities between how they manage physical and logical memory.
查看答案詳解收起答案詳解
解題
Paging and segmentation are both memory management techniques used to implement virtual memory. Similarities: 1. Both allow a program to run even if there is insufficient contiguous physical RAM by swapping blocks of data to and from secondary storage. 2. Both translate virtual memory addresses into physical RAM addresses using lookup tables. Differences: 1. Paging divides physical and logical memory into fixed-size blocks (pages and frames), whereas segmentation divides memory into variable-sized logical blocks (segments) based on the structure of the program (e.g., functions, classes, or arrays). 2. Paging is invisible to the programmer (handled purely by hardware/OS), while segmentation is logical and corresponds to the modular design of the software.
評分準則
Max 2 marks for similarities: - Both enable virtual memory / allow programs to execute without being fully loaded into RAM. - Both map virtual addresses to physical memory locations. - Both can lead to disk thrashing if memory is overloaded. Max 2 marks for differences: - Paging uses fixed-sized blocks, whereas segmentation uses variable-sized blocks. - Pages are physical divisions, whereas segments are logical divisions based on program structure.
題目 21 · structured_theory
4 分
Explain the role of the Network (Internet) Layer and the Transport Layer of the TCP/IP stack when a packet of data is sent across the internet.
查看答案詳解收起答案詳解
解題
The Transport Layer is responsible for establishing end-to-end communication. It splits the application data into smaller segments/packets, adds a sequence number to each, and includes source/destination port numbers to target the correct application. It also handles flow control and error checking. The Network (Internet) Layer takes these packets and prepends IP addresses (source and destination) to the header. It is responsible for routing the packets across the interconnected networks to reach their destination using the most efficient path via routers.
評分準則
Transport Layer (max 2 marks): - 1 mark: Splits data into packets/segments and adds sequence numbers to allow reassembly. - 1 mark: Identifies the correct application using port numbers / handles error checking (retransmission). Network/Internet Layer (max 2 marks): - 1 mark: Adds source and destination IP addresses to the packet header. - 1 mark: Handles routing of packets across different networks using routers.
題目 22 · structured_theory
4 分
Describe the purpose of the 'Atomicity' and 'Durability' properties of ACID in a database transaction system, giving an example of why each is necessary.
查看答案詳解收起答案詳解
解題
Atomicity ensures that a database transaction is treated as a single, indivisible unit of work. Either all operations within the transaction succeed, or none of them do. For example, in a bank transfer of £50 from Account A to Account B, the debit from A and credit to B must both complete. If the system crashes after A is debited but before B is credited, the database rolls back the transaction so money is not lost. Durability ensures that once a transaction is successfully committed, its changes are permanently written to non-volatile storage and will not be lost, even in the event of a subsequent power failure or system crash. For example, once a ticket booking is confirmed, a power failure seconds later must not cause the booking details to be lost from the database.
評分準則
Atomicity (2 marks): - 1 mark: Define Atomicity as the all-or-nothing property of transactions. - 1 mark: Provide a valid example (e.g., bank transfer requiring both debit and credit to succeed or rollback). Durability (2 marks): - 1 mark: Define Durability as ensuring committed transactions are permanently saved and survive system crashes. - 1 mark: Provide a valid example (e.g., flight booking records remaining intact after a server power cut).
題目 23 · structured_theory
4 分
A computer system represents floating-point numbers using an 8-bit mantissa and a 4-bit exponent, both in two's complement. Convert the binary number \(01101000\ 0011\) into a denary number. Show your working.
查看答案詳解收起答案詳解
解題
Step 1: Parse the exponent. The last 4 bits are 0011. Since the sign bit is 0, this is positive. In denary, 0011 = 3. Step 2: Parse the mantissa. The first 8 bits are 01101000. It is positive, so the implied binary point is after the sign bit: 0.1101000. Step 3: Apply the exponent of +3 by shifting the binary point 3 places to the right: 0.1101000 becomes 110.1000 (or 110.1 in binary). Step 4: Convert 110.1 binary to denary. The integer part is 110 (which is 4 + 2 = 6). The fractional part is .1 (which is 0.5). Therefore, the denary number is 6.5.
評分準則
1 mark: Correctly convert the exponent 0011 to denary +3. 1 mark: Correctly identify the mantissa as 0.1101 (or 0.1101000). 1 mark: Correctly show the application of the exponent, e.g., shifting binary point 3 places to get 110.1 binary (or equivalent sum such as 0.8125 x 8). 1 mark: Correct final denary answer 6.5 (or 6 and a half).
題目 24 · structured_theory
4 分
State the main functional difference between a hashing algorithm and a symmetric encryption algorithm, and explain one appropriate use case for each in a secure system.
查看答案詳解收起答案詳解
解題
The main difference is reversibility. A hashing algorithm is a one-way function; once plaintext is converted to a hash value, it cannot be run backward to retrieve the original plaintext. Symmetric encryption is a two-way function; data encrypted with a key can be decrypted back to the original plaintext using the same secret key. Hashing Use Case: Storing user passwords. When a user creates a password, its hash is stored. When they log in, the input is hashed and compared to the stored hash. The original password is never stored, maintaining security. Symmetric Encryption Use Case: Encrypting local files/hard drives or confidential data in transit where both the sender and recipient have secure access to the shared key and need to read the actual data.
評分準則
1 mark: Explain that hashing is one-way / irreversible. 1 mark: Explain that symmetric encryption is two-way / reversible (with a key). 1 mark: Provide a valid hashing use case (e.g., password storage, verifying database integrity / checksums). 1 mark: Provide a valid symmetric encryption use case (e.g., database file encryption, secure messaging where key is pre-shared, hard drive encryption).
題目 25 · structured_theory
4 分
Explain how web crawler (spider) software and indexing are used by search engines to allow users to search the World Wide Web efficiently.
查看答案詳解收起答案詳解
解題
Web crawlers (or spiders) are automated programs that systematically navigate the internet. They start with a list of known URLs, download the content of these pages, and extract any links found within them to add to their queue of pages to visit. Indexing software takes the raw page data downloaded by the crawlers, parses the text to extract keywords, metadata, and page structure. It then constructs or updates an index (a massive, optimized database) that maps these keywords to the URLs on which they appear, along with weighting factors. This ensures that when a user searches for a term, the search engine queries the index rather than the live web, returning relevant results in milliseconds.
評分準則
Max 2 marks for Web Crawlers: - 1 mark: Systematically traverse the web by following hyperlinks from page to page. - 1 mark: Download/fetch the contents / HTML of the visited web pages. Max 2 marks for Indexing: - 1 mark: Parse downloaded text to extract keywords, metadata, and structural features. - 1 mark: Store this in an index / database mapping keywords to their source URLs to allow instant querying.
題目 26 · structured_theory
4 分
The Regulation of Investigatory Powers Act 2000 (RIPA) provides public bodies with certain powers regarding digital communications. State four powers granted to authorities under RIPA.
查看答案詳解收起答案詳解
解題
Under RIPA, authorized public bodies (like police or security services) can: 1. Intercept communications in transit (e.g., monitor emails, phone calls, or internet traffic). 2. Force Internet Service Providers (ISPs) to collect and hand over communications data (metadata like logs of who contacted whom and when). 3. Demand that suspect individuals or organizations decrypt ciphertext or hand over their private encryption keys. 4. Impose strict secrecy on these actions, preventing individuals or companies from revealing that an interception warrant or decryption request has been issued.
評分準則
1 mark per valid power stated (max 4): - Demand ISPs/telecommunication companies hand over a user's communications data (metadata / activity logs). - Intercept / monitor digital communications in transit (e.g. emails, web traffic). - Demand individuals/organizations hand over encryption keys or decrypt encrypted data. - Prevent disclosure of interception/decryption activities (secrecy / gagging orders). - Conduct covert surveillance of internet activities.
題目 27 · structured_theory
4 分
A systems developer is designing an operating system for a new desktop computer. They are deciding whether to use paging or segmentation for memory management. Describe two key differences between paging and segmentation.
查看答案詳解收起答案詳解
解題
Paging and segmentation are both virtual memory management techniques. Paging divides memory into fixed-sized blocks (physical divisions) known as pages/page frames. It is transparent to the programmer. In contrast, segmentation divides memory into variable-sized blocks (logical divisions) called segments, which represent logical divisions of a program (such as functions, objects, or arrays) and are visible to the developer/compiler.
評分準則
1 mark per difference identified and 1 mark per expansion/contrast (Max 4 marks total): - Paging uses fixed-sized blocks/pages (1 mark) whereas segmentation uses variable-sized blocks/segments (1 mark). - Paging is a physical division of memory / handled by the hardware/OS (1 mark) whereas segmentation is a logical division / reflects the structure of the program (1 mark). - Paging is transparent to the programmer (1 mark) whereas segmentation is visible to the programmer/compiler (1 mark).
題目 28 · structured_theory
4 分
Explain how a stateful inspection firewall provides better security for a network compared to a simple packet-filtering firewall.
查看答案詳解收起答案詳解
解題
A simple packet-filtering firewall inspects packets individually and in isolation, checking only static fields in the header (e.g., source/destination IP, port number, protocol) against a set of rules. A stateful inspection firewall tracks the context/state of active network connections (e.g., TCP handshakes). It keeps a state table and only permits incoming packets if they are part of an existing, legitimate conversation initiated from inside the network, preventing many types of unauthorized access and spoofing attacks.
評分準則
1 mark: Packet filtering inspects packet headers (IP addresses/ports) in isolation / statically. 1 mark: Packet filtering does not keep track of the history or state of the connection. 1 mark: Stateful inspection monitors and records active connections/sessions (using a state table). 1 mark: Stateful inspection only allows incoming packets if they match a valid, pre-established outbound request/session.
題目 29 · structured_theory
4 分
A database server is required to perform cryptographic hashing on millions of passwords simultaneously. Explain why a Graphics Processing Unit (GPU) is highly suited for this task compared to a high-performance Central Processing Unit (CPU).
查看答案詳解收起答案詳解
解題
CPUs are designed for general-purpose sequential processing and contain a few highly powerful cores. In contrast, GPUs have a highly parallel architecture containing thousands of smaller, simpler cores designed to handle multiple tasks concurrently. Hashing millions of passwords is a Single Instruction Multiple Data (SIMD) scenario because the exact same hashing algorithm is run on different data inputs (passwords) independently. The massive parallelism of the GPU allows thousands of password hashes to be computed at the exact same time, dramatically outperforming a CPU.
評分準則
1 mark: GPU has a highly parallel architecture / contains thousands of smaller, simpler cores (compared to CPU's few, powerful cores). 1 mark: Identifies that password hashing is a parallelizable task / can be calculated independently (Single Instruction Multiple Data / SIMD). 1 mark: GPU can run the same instructions on multiple streams of data concurrently. 1 mark: This leads to significantly higher throughput/speed for this specific bulk task on a GPU.
題目 30 · structured_theory
4 分
A floating-point system uses an 8-bit normalized two's complement mantissa and a 4-bit two's complement exponent. Represent the denary value \(-3.75\) in this format. Show your working.
查看答案詳解收起答案詳解
解題
1. Convert the magnitude to binary: \(3.75 = 3 + 0.5 + 0.25 = 11.11_2\). 2. Represent as a negative fixed-point number in two's complement. If positive is \(0011.1100\), we flip the bits to get \(1100.0011\) and add 1 to get \(1100.0100\). 3. Normalize the binary number. For negative numbers, a normalized mantissa must start with `10`. The binary point must be placed after the first bit: \(1.0001000\). 4. Calculate the exponent: We moved the binary point 2 places to the left, which means we must multiply the mantissa by \(2^2\). Therefore, the exponent is \(+2\). 5. Convert the exponent to 4-bit two's complement: \(0010\). 6. Combined representation: Mantissa = `10001000`, Exponent = `0010`.
評分準則
1 mark: Converting \(-3.75\) to a valid fixed-point two's complement binary representation (e.g., \(1100.01\) or \(1100.0100\)). 1 mark: Recognizing the need to normalize to a form starting with `10` for a negative number / shifting point 2 places to the left. 1 mark: Correct 8-bit mantissa: `10001000`. 1 mark: Correct 4-bit exponent: `0010`.
題目 31 · extended_essay
10 分
An operating system uses memory management to manage the computer's primary memory. Discuss the differences between paging and segmentation. In your answer, you should also explain how virtual memory works and discuss the potential issues that can arise when virtual memory is heavily relied upon.
查看答案詳解收起答案詳解
解題
Paging and segmentation are two distinct memory management techniques used by an operating system to manage physical memory (RAM). Paging divides physical memory into fixed-size, physical blocks called pages. These pages do not respect the logical structure of a program; a single function or data structure might span multiple pages. Paging can lead to internal fragmentation, where a process does not fully utilize the last page allocated to it. In contrast, segmentation divides memory into variable-size, logical blocks called segments. These segments align with the structure of the program (e.g., individual subroutines, modules, or stack structures). Segmentation can lead to external fragmentation, where free memory is split into small, non-contiguous blocks that cannot accommodate a new segment. Virtual memory is a technique used when RAM is insufficient to hold all active processes. The operating system allocates a portion of secondary storage (such as a hard disk or solid-state drive) to act as temporary RAM. When RAM is full, inactive pages or segments are copied (swapped) from RAM to the virtual memory area on the secondary storage, freeing up space in RAM for active processes. If an inactive page is needed again, it is swapped back into RAM, and another inactive page is moved to secondary storage. While virtual memory allows a computer to run programs that exceed physical memory limits, heavy reliance on it causes performance issues. Secondary storage is significantly slower than RAM, leading to latency. If the system is constantly swapping pages back and forth because RAM is almost entirely full, a phenomenon called 'disk thrashing' occurs. During thrashing, the system spends more time and processing power performing I/O operations (swapping) than executing actual program instructions, causing the computer to become highly unresponsive.
評分準則
Level 3 (8-10 marks): Thorough discussion of both paging and segmentation, showing clear understanding of differences (logical vs physical). Detailed explanation of virtual memory mechanism and a clear, well-reasoned discussion of the drawbacks (including thrashing). Line of reasoning is logical, structured, and technically accurate. Level 2 (5-7 marks): Good discussion of paging and/or segmentation. Explains virtual memory well. Mentions some drawbacks but may lack detail or depth on thrashing. Line of reasoning is generally clear. Level 1 (1-4 marks): Basic definitions of paging/segmentation. Simple mention of virtual memory. Limited awareness of drawbacks. 0 marks: No worthy content.
題目 32 · extended_essay
10 分
A school group manages student records, fee payments, and exam entries using multiple independent flat-file spreadsheets across different regional campuses. They plan to transition to a centralized Relational Database Management System (RDBMS). Evaluate the decision to transition to an RDBMS. Your evaluation should discuss data integrity, data redundancy, security, concurrent access, and any potential challenges the school group might face.
查看答案詳解收起答案詳解
解題
Transitioning from decentralized flat-file spreadsheets to a centralized Relational Database Management System (RDBMS) offers significant advantages alongside some implementation challenges. Firstly, flat-file systems suffer from high data redundancy because the same student details must be repeated across separate fee, exam, and attendance spreadsheets. This redundancy leads to poor data integrity; if a student changes their address, updating it in one spreadsheet does not automatically update it in others, causing inconsistencies. An RDBMS addresses this through normalization, storing data in linked, non-redundant tables. Referential integrity is enforced using primary and foreign keys, ensuring that records cannot point to non-existent data. Secondly, security is highly limited in flat-file spreadsheets, which are often either fully accessible or fully locked. An RDBMS offers robust, granular security, allowing administrators to set specific database access permissions (e.g., teachers can view grades but not change payroll). It also supports views, presenting only relevant data to specific users. Thirdly, flat-files do not support concurrent access effectively; if multiple users attempt to edit a spreadsheet simultaneously, conflicts and data loss occur. An RDBMS handles concurrent access safely using record locking, preventing two users from updating the same record at the same time. However, the school group must consider several challenges: the significant initial cost of database software licenses and server infrastructure, the necessity of training administrative staff to write SQL queries or use the new interface, and the high complexity of cleansing and migrating fragmented legacy data into a structured relational schema without causing system downtime.
評分準則
Level 3 (8-10 marks): Comprehensive evaluation covering all requested areas (integrity, redundancy, security, concurrency, challenges). Clear contrast between flat-files and RDBMS. Technical terminology (e.g., referential integrity, normalization, record locking, views) used accurately. Level 2 (5-7 marks): Good evaluation addressing most areas. Clearly identifies advantages of RDBMS over flat-files. Explains at least one challenge. Some technical terminology used. Level 1 (1-4 marks): Basic points made about databases vs spreadsheets. Limited range of discussion or purely descriptive without evaluation.
題目 33 · extended_essay
10 分
A healthcare trust plans to introduce an automated, machine-learning-based triage system to assess and prioritize patients in emergency departments. Discuss the ethical, moral, and legal issues that the trust must consider before deploying this system.
查看答案詳解收起答案詳解
解題
Deploying an automated machine-learning triage system in a healthcare trust raises critical ethical, moral, and legal questions. Ethically, the primary concern is algorithmic bias. Machine learning models learn from historical data; if this data contains biases (e.g., under-prioritizing or misdiagnosing minority groups due to historical systemic biases), the AI will replicate and entrench these inequalities. Another ethical issue is accountability and transparency: if a patient is mis-triaged and suffers harm, is the programmer, the medical trust, or the supervising clinician responsible? Furthermore, 'black box' deep learning models offer low explainability, meaning doctors cannot easily understand why a particular priority level was assigned. Morally, healthcare is built on empathy, compassion, and human connection. An automated system lacks the ability to sense subtle, non-verbal cues of distress or exhibit empathy, which are crucial in a clinical setting. It also risks dehumanizing patient care, making patients feel like numbers in a queue, and could lead to the deskilling of triage nurses whose diagnostic intuition is replaced by algorithms. Legally, the system must comply with data protection legislation, such as the UK Data Protection Act 2018 / GDPR. Triage involves highly sensitive special-category health data, requiring strict encryption, robust access controls, and explicit patient consent. Under GDPR, patients also have the right not to be subject to a decision based solely on automated processing, meaning there must always be a practical mechanism for human review. Additionally, the trust faces complex medical negligence liability issues if the software malfunctions, and potential violations of the Equality Act if the algorithm discriminates against protected characteristics.
評分準則
Level 3 (8-10 marks): Balanced and mature discussion covering Ethical, Moral, and Legal issues thoroughly in the context of healthcare. Specific legal acts (e.g., GDPR/DPA, Equality Act) and concepts (accountability, algorithmic bias, consent, human oversight) are discussed clearly. Clear, logical line of reasoning. Level 2 (5-7 marks): Covers at least two of the three areas (ethical, moral, legal) with reasonable detail. Some relevant legal/ethical concepts mentioned. Line of reasoning is generally clear. Level 1 (1-4 marks): Simple points or general comments about AI in medicine without clearly distinguishing ethical, moral, or legal factors. Limited technical or legal terminology.
卷二 甲部 (H446/02 甲部)
Answer all questions. Testing computational thinking, algorithmic trace, and algorithmic design.
24 題目 · 85 分
題目 1 · short_answer
2 分
A GPS navigation application uses abstraction when displaying a route to a driver. Describe two ways the application uses abstraction.
查看答案詳解收起答案詳解
解題
Abstraction simplifies the map by hiding details that are not relevant to navigation. First, the map removes complex visual distractions like building facades, greenery, or altitude variations. Second, the system simplifies the display by rendering only roads, major landmarks, and path directions to help the driver navigate efficiently.
評分準則
One mark for identifying a detail that is removed (e.g., scenery, buildings). One mark for identifying a detail that is retained or simplified (e.g., road names, path direction).
題目 2 · short_answer
2 分
State the output of the recursive function puzzle(5) using the pseudocode below:
function puzzle(n) if n <= 1 then return 1 else return n * puzzle(n - 2) endif endfunction
Show your working.
查看答案詳解收起答案詳解
解題
The execution trace is as follows: puzzle(5) returns 5 * puzzle(3). puzzle(3) returns 3 * puzzle(1). puzzle(1) returns 1. Substituting the values: 5 * 3 * 1 = 15.
評分準則
One mark for showing the correct recursive substitution steps (e.g., 5 * 3 * 1). One mark for the correct final answer of 15.
題目 3 · short_answer
2 分
A binary search tree is constructed by inserting the following integers sequentially: 12, 5, 18, 2, 9. State the pre-order traversal sequence of the resulting tree.
查看答案詳解收起答案詳解
解題
First, construct the tree: 12 is the root. 5 is placed to the left of 12. 18 is placed to the right of 12. 2 is placed to the left of 5. 9 is placed to the right of 5. A pre-order traversal visits nodes in the order: Root, Left, Right. Thus, the sequence is: 12, 5, 2, 9, 18.
評分準則
One mark for correct tree structure or finding the first three nodes (12, 5, 2). One mark for the completely correct sequence: 12, 5, 2, 9, 18.
題目 4 · short_answer
2 分
Explain why local variables are preferred over global variables inside recursive subroutines.
查看答案詳解收起答案詳解
解題
Each recursive call generates a new stack frame on the call stack, which holds a separate instance of the local variables. This keeps their values isolated. If global variables were used, subsequent recursive calls would overwrite the values, leading to incorrect calculations when unwinding the recursion.
評分準則
One mark for mentioning that local variables are allocated on the call stack for each individual call level. One mark for explaining that global variables would be overwritten by subsequent calls, corrupting the calculation.
題目 5 · short_answer
2 分
A programmer is writing a function divide(a, b) that returns the result of dividing two positive integers. State two preconditions that should be documented or checked for this function.
查看答案詳解收起答案詳解
解題
Preconditions define what must be true before a subroutine executes. For this division function, 1) the divisor b must not be zero to avoid a division-by-zero runtime error, and 2) both parameters a and b must be verified as positive integers in line with the specification.
評分準則
One mark for stating that the divisor cannot be zero (or must be greater than zero). One mark for stating that both parameters must be positive integers / valid numeric types.
題目 6 · short_answer
2 分
Describe how backtracking is used by a depth-first search algorithm when finding a path through a maze.
查看答案詳解收起答案詳解
解題
Depth-first search traverses as deep as possible down a path. When it encounters a dead end (no unvisited neighbors), it backtracks by popping nodes off the call stack (or recursion stack) until it returns to a node that has remaining unexplored adjacent edges, continuing the search from there.
評分準則
One mark for identifying that the search retreats/moves backward when a dead end is reached. One mark for stating it goes back to the last node/intersection with unexplored options to continue searching.
題目 7 · short_answer
2 分
A binary search is conducted on a sorted array of 128 elements. Calculate the maximum number of comparisons required to determine if a target value is in the array. Show your working.
查看答案詳解收起答案詳解
解題
At each step, the search space is divided by 2. \(128 = 2^7\). This means there are 7 divisions required to reduce the array to a single element. Testing that final element and verifying success/failure takes at most 8 comparisons in total (or 7 if we only count the split comparisons). Both 7 and 8 are accepted.
評分準則
One mark for showing correct working of repeated halving or log base 2 calculation (e.g. \(128 \rightarrow 64 \rightarrow 32 \rightarrow 16 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1\) or \(\log_2(128) = 7\)). One mark for stating the correct maximum comparisons of 7 or 8.
題目 8 · short_answer
2 分
Describe the difference between concurrent processing and parallel processing.
查看答案詳解收起答案詳解
解題
Concurrent processing is when a single processor switches rapidly between multiple tasks using time-slicing, giving the illusion that they are running simultaneously. Parallel processing is when multiple processors or cores execute different instructions at the exact same physical instant.
評分準則
One mark for explaining concurrent processing as interleaving tasks/time-slicing on a single CPU core. One mark for explaining parallel processing as executing tasks simultaneously across multiple CPU cores or processors.
題目 9 · short_answer
2 分
An algorithm is defined by the following recursive function:
function puzzle(n) if n <= 1 then return 1 elseif n mod 2 == 0 then return n + puzzle(n - 1) else return n * puzzle(n - 2) endif endfunction
State the value returned by the call puzzle(6) and show your working.
查看答案詳解收起答案詳解
解題
To find the value of puzzle(6): 1. Since 6 is even (6 mod 2 == 0), the function returns 6 + puzzle(5). 2. For puzzle(5), 5 is odd, so it returns 5 * puzzle(3). 3. For puzzle(3), 3 is odd, so it returns 3 * puzzle(1). 4. For puzzle(1), the base case n <= 1 is met, returning 1.
Now we substitute these values back: - puzzle(3) = 3 * 1 = 3 - puzzle(5) = 5 * 3 = 15 - puzzle(6) = 6 + 15 = 21.
評分準則
1 mark: Correct intermediate working showing the recursive steps (e.g., showing that puzzle(5) = 15 or showing the expression 6 + (5 * (3 * 1))). 1 mark: Correct final answer of 21.
題目 10 · short_answer
2 分
A software developer is writing a subroutine findAverage(scores) that accepts a 1D array of integers representing student test marks and returns the mean average. Identify two preconditions that should be established before the subroutine executes to ensure it runs correctly and safely.
查看答案詳解收起答案詳解
解題
Preconditions must be satisfied before a subroutine runs to avoid errors. For findAverage(scores): 1. The array must contain at least one element. If the array is empty, dividing the total score by the count of elements (zero) will cause a runtime division-by-zero error. 2. The elements in the array must be of numeric type so that mathematical addition and division operations can be performed without causing a type mismatch error.
評分準則
1 mark per valid precondition identified (max 2): - The array scores is not empty / size of scores > 0. - The array contains only numeric values (integers/reals). - All mark values are within a valid expected range (e.g., non-negative).
題目 11 · short_answer
2 分
Write a pseudocode snippet that iterates through a 1D array of integers named numbers of size N, and counts how many elements are both positive (greater than zero) and even. Store the final count in a variable named count.
查看答案詳解收起答案詳解
解題
An elegant solution involves initializing a counter variable to 0, looping through the indices of the array from 0 to N-1, checking if the element at the current index is both greater than 0 and divisible by 2 with no remainder, and incrementing the counter if both conditions are met.
Example pseudocode: count = 0 for i = 0 to N - 1 if (numbers[i] > 0) and (numbers[i] mod 2 == 0) then count = count + 1 endif next i
評分準則
1 mark: Correct loop structure (from 0 to N-1 or equivalent bounds) and initialisation of count to 0. 1 mark: Correct combined condition check (greater than zero AND even) and incrementing the count variable inside the loop.
題目 12 · short_answer
2 分
An online retail platform processes thousands of customer orders simultaneously. Explain one benefit and one drawback of using concurrent processing instead of sequential processing to manage these orders.
查看答案詳解收起答案詳解
解題
Concurrent processing allows multiple execution threads to make progress in overlapping periods. - Benefit: It drastically improves the responsiveness and capacity of the retail platform. Users do not have to wait in a single sequential queue, allowing thousands of orders to be processed simultaneously. - Drawback: It increases development complexity. Programming must account for concurrency conflicts such as race conditions (e.g., two users purchasing the exact same stock item at the same millisecond) which require record locking mechanisms to avoid data inconsistency.
評分準則
1 mark for a valid benefit (e.g., faster response times for users, higher throughput, better utilization of multi-core CPU resources). 1 mark for a valid drawback (e.g., more complex to write/debug, risk of race conditions, risk of deadlocks, necessity of introducing resource-locking mechanisms).
題目 13 · structured_algorithmic
4 分
The following pseudocode describes a breadth-first search (BFS) algorithm to find the shortest distance (in terms of number of edges) between a start node and a target node in an unweighted graph.
function mystery(graph, startNode, targetNode) queue = new Queue() visited = new Set() queue.enqueue([startNode, 0]) visited.add(startNode) while not queue.isEmpty() currentNode, distance = queue.dequeue() if currentNode == targetNode then return distance endif for neighbor in graph[currentNode] if neighbor is not in visited then visited.add(neighbor) queue.enqueue([neighbor, distance + 1]) endif endfor endwhile return -1 endfunction
An unweighted graph is defined with the following nodes: A, B, C, D, E, F. Its adjacency lists (sorted alphabetically for processing) are: - A: [B, C] - B: [A, D, E] - C: [A, F] - D: [B] - E: [B, F] - F: [C, E]
Trace the execution of the call mystery(graph, "A", "F") and provide: 1. The sequence of nodes dequeued from the queue in order. 2. The final returned value. 3. The contents of the 'visited' set at the start of Iteration 3 (when the 3rd node is about to be dequeued).
查看答案詳解收起答案詳解
解題
We trace the algorithm step-by-step: - Initially, queue contains [[A, 0]], visited set contains {A}. - Iteration 1: Dequeue [A, 0]. currentNode = A, distance = 0. Neighbors of A are B, C. Since both are not in visited, they are added to visited. visited = {A, B, C}. queue = [[B, 1], [C, 1]]. - Iteration 2: Dequeue [B, 1]. currentNode = B, distance = 1. Neighbors of B are A, D, E. A is already visited. D and E are not. They are added to visited. visited = {A, B, C, D, E}. queue = [[C, 1], [D, 2], [E, 2]]. - Iteration 3: Dequeue [C, 1]. currentNode = C, distance = 1. Neighbors of C are A, F. A is visited. F is not. F is added to visited. visited = {A, B, C, D, E, F}. queue = [[D, 2], [E, 2], [F, 2]]. - Iteration 4: Dequeue [D, 2]. currentNode = D, distance = 2. Neighbors of D are B (visited). queue = [[E, 2], [F, 2]]. - Iteration 5: Dequeue [E, 2]. currentNode = E, distance = 2. Neighbors of E are B, F (both visited). queue = [[F, 2]]. - Iteration 6: Dequeue [F, 2]. currentNode = F == targetNode. Return distance = 2.
評分準則
- 1 mark: Correct sequence of dequeued nodes (A, B, C, D, E, F). - 1 mark: Correct final return value (2). - 2 marks: Correct visited set at the start of Iteration 3 (A, B, C, D, E). Deduct 1 mark for any missing or extra node.
題目 14 · structured_algorithmic
4 分
Consider the following recursive algorithm:
function calc(n, m) if n <= 0 or m <= 0 then return n + m elseif n mod 2 == 0 then return calc(n - 1, m - 1) + 2 else return calc(n - 2, m - 1) * 3 endif endfunction
Trace the execution of the function call calc(4, 3) and provide: 1. The value of calc(-1, 0) 2. The value of calc(1, 1) 3. The value of calc(3, 2) 4. The final returned value of calc(4, 3)
查看答案詳解收起答案詳解
解題
We trace the recursive steps in order: 1. calc(4, 3): - Since 4 mod 2 == 0, this returns calc(3, 2) + 2. 2. calc(3, 2): - Since 3 mod 2 != 0, this returns calc(1, 1) * 3. 3. calc(1, 1): - Since 1 mod 2 != 0, this returns calc(-1, 0) * 3. 4. calc(-1, 0): - Since n <= 0 or m <= 0 (where -1 <= 0 and 0 <= 0), this returns n + m = -1 + 0 = -1.
The items ["M", "G", "R", "C", "K", "P", "Y"] are inserted, in the order shown, into an initially empty Binary Search Tree (BST) using standard alphabetical order rules (where A < Z).
1. Identify the parent node of "P". 2. Identify the left and right children of "G". 3. Perform a post-order traversal (Left, Right, Root) of this completed tree and write the sequence of nodes visited.
查看答案詳解收起答案詳解
解題
Let's construct the Binary Search Tree: 1. "M" is the root. 2. "G" < "M" -> left child of "M". 3. "R" > "M" -> right child of "M". 4. "C" < "M", "C" < "G" -> left child of "G". 5. "K" < "M", "K" > "G" -> right child of "G". 6. "P" > "M", "P" < "R" -> left child of "R". 7. "Y" > "M", "Y" > "R" -> right child of "R".
From this tree: - The parent of "P" is "R". - The children of "G" are "C" (left) and "K" (right).
Post-order traversal (Left, Right, Root): - Left subtree of "M" rooted at "G": - Left child: "C" (visited) - Right child: "K" (visited) - Root: "G" (visited) - Subtree sequence: C, K, G - Right subtree of "M" rooted at "R": - Left child: "P" (visited) - Right child: "Y" (visited) - Root: "R" (visited) - Subtree sequence: P, Y, R - Root of tree: "M" (visited) - Complete sequence: C, K, G, P, Y, R, M.
評分準則
- 1 mark: Correctly identifies R as the parent of P. - 1 mark: Correctly identifies C and K as the left and right children of G. - 2 marks: Correct post-order traversal sequence: C, K, G, P, Y, R, M (1 mark for a sequence with at most two ordering errors).
題目 16 · structured_algorithmic
4 分
A program contains the following procedure and main routine:
procedure process(byRef array, byVal index, byRef val) val = val + array[index] array[index] = array[index] * 2 index = index + 1 endprocedure
Analyze the execution of main() and answer the following: 1. What is the value of num after the procedure process has finished executing? 2. What is the value of idx after the procedure process has finished executing? 3. What is the value of myArray[1] after the procedure process has finished executing? 4. Explain why the value of the variable idx remains unchanged after the procedure call.
查看答案詳解收起答案詳解
解題
We trace the execution step-by-step: - myArray is passed by reference, so any changes to array within the procedure affect myArray directly. - idx (value 1) is passed by value, meaning the parameter index gets a copy (value 1) and any changes to index will not affect idx. - num (value 5) is passed by reference, meaning the parameter val directly references num.
Inside process: 1. val = val + array[index] => val = 5 + myArray[1] = 5 + 20 = 25. Since val is a reference to num, num is updated to 25. 2. array[index] = array[index] * 2 => myArray[1] = 20 * 2 = 40. 3. index = index + 1 => index = 1 + 1 = 2. Since index is passed by value, this change is local to process.
After process finishes: - num is 25. - idx remains 1. - myArray[1] is 40.
評分準則
- 1 mark: Correct value of num (25). - 1 mark: Correct value of idx (1). - 1 mark: Correct value of myArray[1] (40). - 1 mark: Correct explanation of pass-by-value mechanism preventing modification of the original argument idx.
題目 17 · structured_algorithmic
4 分
A circular queue of capacity 5 (using indices 0 to 4) is implemented using an array, a head pointer, a tail pointer, and a size variable. The queue is initially empty (head = 0, tail = 0, size = 0, and all array elements are Null).
The following operations are performed in order: 1. enqueue("A") 2. enqueue("B") 3. enqueue("C") 4. dequeue() 5. enqueue("D") 6. enqueue("E") 7. dequeue() 8. enqueue("F")
Assume standard circular queue behavior, where: - enqueue(item): places the item at array[tail], increments tail modulo 5, and increments size. - dequeue(): stores array[head], clears array[head] to Null, increments head modulo 5, decrements size, and returns the stored item.
Provide the final state of the queue by stating: 1. The final value of head. 2. The final value of tail. 3. The elements stored in the array at each index from 0 to 4.
Final queue array: ["F", Null, "C", "D", "E"], head = 2, tail = 1, size = 4.
評分準則
- 1 mark: Correct final head value (2). - 1 mark: Correct final tail value (1). - 2 marks: Correct elements at each index of the array: index 0: "F", index 1: Null (or empty), index 2: "C", index 3: "D", index 4: "E" (deduct 1 mark for any incorrect element).
題目 18 · structured_algorithmic
4 分
An array of integers [15, 4, 8, 11, 2] is sorted using the following Insertion Sort algorithm:
for i = 1 to len(array) - 1 key = array[i] j = i - 1 while j >= 0 and array[j] > key array[j + 1] = array[j] j = j - 1 endwhile array[j + 1] = key next i
Trace the state of the array after each pass of the outer loop: 1. What is the state of the array after the first pass (i = 1)? 2. What is the state of the array after the second pass (i = 2)? 3. What is the state of the array after the third pass (i = 3)? 4. What is the final sorted array (i = 4)?
查看答案詳解收起答案詳解
解題
Let's trace the Insertion Sort: - Initial: [15, 4, 8, 11, 2] - Pass 1 (i = 1, key = 4): Compare with 15. Shift 15 right. Insert 4. Array: [4, 15, 8, 11, 2] - Pass 2 (i = 2, key = 8): Compare with 15. Shift 15. Compare with 4 (no shift). Insert 8. Array: [4, 8, 15, 11, 2] - Pass 3 (i = 3, key = 11): Compare with 15. Shift 15. Compare with 8 (no shift). Insert 11. Array: [4, 8, 11, 15, 2] - Pass 4 (i = 4, key = 2): Compare with 15, 11, 8, 4. Shift all right. Insert 2 at index 0. Array: [2, 4, 8, 11, 15]
評分準則
- 1 mark: Correct state after Pass 1 ([4, 15, 8, 11, 2]). - 1 mark: Correct state after Pass 2 ([4, 8, 15, 11, 2]). - 1 mark: Correct state after Pass 3 ([4, 8, 11, 15, 2]). - 1 mark: Correct state after Pass 4 ([2, 4, 8, 11, 15]).
題目 19 · structured_algorithmic
4 分
A recursive depth-first backtracking search algorithm is used to find a path through a 3x3 grid from (0,0) to (2,2). Grid cells contain 1 for a wall and 0 for an open path: - Row 0: [0, 0, 1] - Row 1: [1, 0, 0] - Row 2: [0, 1, 0]
The search function prioritizes directional moves in the order: Right, Down, Left, Up. Once a cell is visited, it is marked as visited. If a path fails, it backtracks. The algorithm terminates as soon as cell (2,2) is reached.
Analyze the search and answer: 1. What is the ordered list of coordinates (row, col) in the successful path found by the algorithm? 2. What was the coordinate of the first wall (1) encountered and rejected during the search? 3. Explain why the open cell at coordinate (2,0) was never visited during the execution of this algorithm.
查看答案詳解收起答案詳解
解題
Let's trace the DFS backtracking pathfinder: - Start at (0,0). - Try Right: moves to (0,1) (success, open). - From (0,1), try Right: moves to (0,2) (fails, wall at (0,2)). - From (0,1), try Down: moves to (1,1) (success, open). - From (1,1), try Right: moves to (1,2) (success, open). - From (1,2), try Right: out of bounds (fails). - From (1,2), try Down: moves to (2,2) (success, target reached!).
The successful path consists of cells: (0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2). - The first wall encountered was at (0,2). - The open cell at (2,0) was never visited because the search found a valid path to the target (2,2) without backtracking to search other directions (such as going down from (0,0), which was blocked by a wall at (1,0) anyway, or backtracking to other start branches).
評分準則
- 2 marks: Correct coordinates of the path in order. (Deduct 1 mark for any missing/incorrect coordinates). - 1 mark: Correctly identifies (0,2) as the first wall encountered. - 1 mark: Explains that (2,0) is not visited because a path to (2,2) is successfully found first, preventing further exploration/backtracking.
題目 20 · structured_algorithmic
4 分
The following algorithm normalizes a 4-bit two's complement fractional mantissa and its integer exponent.
function normalize(mantissa, exponent) while true firstTwoBits = getFirstTwoBits(mantissa) // e.g. "00", "01", "10", "11" if firstTwoBits == "01" or firstTwoBits == "10" then return [mantissa, exponent] endif mantissa = shiftLeft(mantissa) // Shifts left by 1 bit, appending a "0" on the right exponent = exponent - 1 endwhile endfunction
Trace the execution of this algorithm for: 1. Case A: mantissa = "0001", exponent = 3 2. Case B: mantissa = "1110", exponent = -2
For each case, show any intermediate step(s) and state the final returned [mantissa, exponent] pair.
查看答案詳解收起答案詳解
解題
We trace the algorithm step-by-step for each case:
- 2 marks: Case A (1 mark for showing intermediate mantissa "0010" / exponent 2; 1 mark for correct final output ["0100", 1]). - 2 marks: Case B (1 mark for showing intermediate mantissa "1100" / exponent -3; 1 mark for correct final output ["1000", -4]).
題目 21 · structured_algorithmic
4 分
A programmer designs the following recursive function `crunch`:
``` function crunch(n, k) if n <= 0 then return k elseif n % 3 == 0 then return crunch(n - 3, k + 2) else return crunch(n - 1, k * 2) endif endfunction ```
Trace the execution of `crunch(8, 2)` by stating: 1. Every recursive call made (with its arguments) in the correct chronological order. 2. The final returned value.
查看答案詳解收起答案詳解
解題
We trace each step of the recursive calls: - Initial Call: `crunch(8, 2)`. Because 8 is not <= 0 and 8 % 3 != 0, we call `crunch(8 - 1, 2 * 2)` which evaluates to `crunch(7, 4)`. - First recursive call: `crunch(7, 4)`. Because 7 % 3 != 0, we call `crunch(7 - 1, 4 * 2)` which evaluates to `crunch(6, 8)`. - Second recursive call: `crunch(6, 8)`. Since 6 % 3 == 0, we call `crunch(6 - 3, 8 + 2)` which evaluates to `crunch(3, 10)`. - Third recursive call: `crunch(3, 10)`. Since 3 % 3 == 0, we call `crunch(3 - 3, 10 + 2)` which evaluates to `crunch(0, 12)`. - Fourth recursive call: `crunch(0, 12)`. Since 0 <= 0, this returns `k` which is 12.
The progression is `crunch(7, 4)` -> `crunch(6, 8)` -> `crunch(3, 10)` -> `crunch(0, 12)` which eventually returns 12.
評分準則
1 Mark: Identifies the first recursive call `crunch(7, 4)` (or shows parameter values 7 and 4). 1 Mark: Identifies the second recursive call `crunch(6, 8)`. 1 Mark: Identifies both subsequent recursive calls: `crunch(3, 10)` and `crunch(0, 12)` in order. 1 Mark: States the correct final returned value of 12.
題目 22 · structured_algorithmic
4 分
A programmer is designing an algorithm to perform a single pass of a Bubble Sort on an array of integers named `items` containing \(n\) elements (indexed from \(0\) to \(n-1\)).
The single pass must iterate through the array, compare adjacent elements, and swap them if they are in the incorrect order (ascending order is expected).
Write pseudocode to perform this single pass of a Bubble Sort. Assume the array `items` and its size \(n\) are already defined and accessible.
查看答案詳解收起答案詳解
解題
A single pass of Bubble Sort compares adjacent items starting from the beginning of the array.
We loop from index 0 up to \(n-2\) because we compare `items[i]` with the adjacent element `items[i+1]`. Stopping at \(n-2\) prevents an index-out-of-bounds error.
Inside the loop, we check if `items[i] > items[i+1]`. If so, we perform a standard swap operation utilizing a temporary variable (`temp`) to store one of the values so it is not overwritten.
評分準則
1 Mark: Correct loop boundaries that visit all adjacent elements without exceeding array limits (e.g., from 0 to \(n-2\) or 1 to \(n-1\)). 1 Mark: Correct comparison of adjacent items (e.g., `items[i] > items[i+1]` or equivalent logic based on loop variable). 1 Mark: Use of a temporary variable to hold one of the values during the swap sequence. 1 Mark: Correct assignment of both swapped elements to complete the swap sequence safely.
題目 23 · extended_essay
10.5 分
A software engineer is developing a pathfinding algorithm for an autonomous warehouse robot. The robot must navigate a 2D grid-based floorplan consisting of open paths, obstacles, and various delivery points. The engineer is deciding whether to implement a Depth-First Search (DFS) or a Breadth-First Search (BFS) algorithm to find a path from the charging station to a target delivery point.
Discuss the suitability of Depth-First Search (DFS) and Breadth-First Search (BFS) for this scenario. Your answer should compare: - The search strategies of both algorithms and their visual representation in terms of traversal. - The underlying data structures required to implement each algorithm. - The time and space complexities, including how the structures of the warehouse layout might affect performance. - The capability of each algorithm to guarantee the shortest path to a delivery point.
查看答案詳解收起答案詳解
解題
### 1. Search Strategies and Traversal - **Breadth-First Search (BFS)**: Explores the grid level-by-level, starting from the source node (charging station) and visiting all immediate neighbors before moving to the neighbors' neighbors. Visually, this looks like a ripple expanding outwards across the grid. - **Depth-First Search (DFS)**: Explores a single path as deeply as possible, moving from neighbor to neighbor until a dead-end or obstacle is met, then backtracking to the last node with unexplored branches. Visually, this is a single winding line probing deep into the grid.
### 2. Underlying Data Structures - **BFS** relies on a **Queue** (First-In, First-Out / FIFO) structure. Discovered nodes are appended to the back, and the next node to explore is dequeued from the front. - **DFS** relies on a **Stack** (Last-In, First-Out / LIFO) structure. Nodes are pushed onto the stack as they are discovered and popped off to be explored. This can be implemented explicitly using a stack structure or implicitly using the call stack via a recursive function. - Both algorithms also require a data structure (such as a 2D array of booleans or a hash set) to track 'visited' nodes to prevent infinite loops in grids with cycles.
### 3. Time and Space Complexities - **Time Complexity**: Both algorithms have a worst-case time complexity of \(O(V + E)\), where \(V\) is the number of open grid cells (vertices) and \(E\) is the number of possible directional movements between adjacent cells (edges). In a dense grid, \(E \approx 4V\). - **Space Complexity**: - BFS: \(O(V)\) in the worst case, as the queue must store the 'frontier' of the expanding wave. In an open grid layout, the frontier grows proportionally to the perimeter of the search space. - DFS: \(O(V)\) in the worst case (e.g., a single long winding corridor with no branches). However, on average, the call stack size is limited to the maximum depth of the search path.
### 4. Shortest Path Guarantee & Warehouse Application - **BFS** guarantees finding the shortest path (fewest cells) in an unweighted grid because it explores nodes in order of their distance from the source. This is crucial for a warehouse robot to minimize travel time and battery usage. - **DFS** does not guarantee the shortest path. It will return the first path it finds to the target, which could be extremely long and convoluted, making it highly inefficient for warehouse operation.
評分準則
### Level 3 (9 - 10.5 Marks) - Comprehensive comparison of both search strategies and visual patterns. - Correctly identifies and details the Queue (FIFO) for BFS and Stack (LIFO) / recursion for DFS, noting the necessity of tracking visited states. - Accurately analyzes the time \(O(V + E)\) and space complexities of both algorithms, relating them directly to grid characteristics. - Provides a clear and definitive argument for why BFS guarantees the shortest path whereas DFS does not, and links this to the practical performance of the warehouse robot. - Logic is coherent, well-structured, and rich in technical vocabulary.
### Level 2 (5 - 8 Marks) - Good comparison of DFS and BFS, though some aspects (like visited tracking or specific visual descriptions) may be brief. - Correctly maps algorithms to Stack and Queue structures. - Identifies the basic complexities, although the distinction in space complexity behavior in grids may lack depth. - Clearly states that BFS guarantees the shortest path while DFS does not, with some application to the warehouse context. - Structured and generally fluent, with minor omissions in detail.
### Level 1 (1 - 4 Marks) - Basic identification of the two algorithms and their traversal mechanisms. - May confuse the underlying data structures or fail to mention the visited list. - Mentions complexities with errors, or provides a superficial comparison. - Weak or missing link to the warehouse robot scenario. - Lacks structure and relies on highly generalized descriptions.
### 0 Marks - No creditworthy response provided.
題目 24 · extended_essay
10.5 分
A software company is redesigning a high-performance database management system. To speed up the sorting of massive log datasets (containing billions of records), the development team proposes replacing their sequential Merge Sort implementation with a concurrent/parallelized Merge Sort that runs across multiple CPU cores.
Discuss the benefits, trade-offs, and limitations of implementing a concurrent sorting algorithm compared to a sequential one. Your discussion should include: - How concurrent processing is applied to a divide-and-conquer algorithm like Merge Sort. - The hardware and software requirements or mechanisms needed to manage concurrent execution (e.g., threads, scheduling, synchronization). - Potential synchronization issues and hazards, such as race conditions and deadlocks, and how they can be mitigated. - The theoretical limitations on speedup as defined by Amdahl's Law.
查看答案詳解收起答案詳解
解題
### 1. Application of Concurrency to Merge Sort Merge Sort is inherently suited to concurrent execution due to its divide-and-conquer nature. In a sequential implementation, the array is split, the left half is recursively sorted, then the right half, and finally, they are merged. In a concurrent implementation: - The sorting of the left and right halves can be spawned as independent parallel threads running concurrently on separate CPU cores. - This parallel division can continue recursively down the tree. - A threshold (or 'cutoff') is typically set: when a sub-array becomes small enough, the algorithm switches to sequential merge sort (or insertion sort) to prevent thread-creation overhead from outweighing the performance gains.
### 2. Hardware and Software Mechanisms - **Hardware**: Requires a multi-core or multi-processor architecture to achieve true physical parallelism. On single-core systems, concurrency is simulated via time-slicing, which would actually degrade sorting performance due to context-switching overhead. - **Software**: A thread-scheduler (within the OS or runtime environment) maps threads to physical CPU cores. High-level frameworks like Fork/Join pools are often used to manage a fixed set of worker threads, avoiding the heavy cost of repeatedly creating and destroying OS-level threads.
### 3. Synchronization Issues, Hazards, and Mitigation - **Race Conditions**: Occur when multiple threads attempt to access and modify the same memory location simultaneously. In Merge Sort, if threads write to shared indices of a target array or use shared counters without synchronization, the output will be corrupted. Mitigation: Threads must operate on strictly non-overlapping slices of memory, or access must be controlled using locks/semaphores. - **Deadlocks**: Can occur if threads are blocked waiting for locks held by other threads. Mitigation: A fork-join design minimizes locks by keeping threads isolated to their own memory segments, only synchronizing at defined 'join' barrier points where a parent thread waits for child threads to complete. - **Resource Exhaustion**: Creating too many threads can exhaust system memory. Mitigation: Implement a thread pool to limit the maximum number of concurrent active threads.
### 4. Amdahl's Law and Speedup Limits Amdahl's Law calculates the maximum theoretical speedup \(S_{\text{latency}}\) of a program using \(N\) processors: \[S_{\text{latency}}(s) = \frac{1}{(1-p) + \frac{p}{s}}\] where \(p\) is the proportion of execution time that can be parallelized, and \(s\) is the speedup factor of that portion (e.g., the number of cores \(N\)). - In parallel Merge Sort, the merging phase at the very top of the recursion tree requires merging two fully sorted halves. This final step is inherently sequential and must process all \(n\) elements. This sequential bottleneck represents the \(1-p\) component. - As the number of processor cores approaches infinity, the execution time approaches the sequential merge bottleneck. Thus, Amdahl's Law proves that the algorithm cannot achieve linear speedup, and the benefits of adding more cores diminish rapidly.
評分準則
### Level 3 (9 - 10.5 Marks) - Clearly explains how Merge Sort's divide-and-conquer strategy naturally translates to concurrent execution, detailing recursion and thread-cutoff thresholds. - Discusses multi-core hardware requirements, OS-level scheduling, and software-level fork/join or thread pool abstractions. - Demonstrates deep understanding of concurrency hazards, correctly explaining race conditions and deadlocks, with explicit, valid mitigation strategies (e.g., thread isolation, join barriers, locks). - Accurately details Amdahl's Law (including its mathematical formula/logic) and applies it to Merge Sort, identifying the final sequential merge phase as the key bottleneck. - Writing is coherent, logically structured, and presents sophisticated technical terminology throughout.
### Level 2 (5 - 8 Marks) - Explains the concept of splitting the sorting work into parallel threads. - Mentions hardware/software requirements such as multi-core CPUs and basic thread management. - Identifies race conditions and deadlocks, offering general mitigation methods. - Mentions Amdahl's Law and notes that speedup is limited by sequential portions of the code, though the connection to the final merge step or the mathematical representation may be slightly hand-waved. - Good structure with mostly accurate technical terms.
### Level 1 (1 - 4 Marks) - Basic description of concurrent processing (e.g., doing things at the same time). - Mentions threads but lacks clarity on how Merge Sort is parallelized. - Mentions race conditions or deadlocks without clear definitions or solutions. - Superficial or no mention of Amdahl's Law and its limitations. - Unstructured, relying on high-level general knowledge without technical depth.
### 0 Marks - No creditworthy response provided.
卷二 乙部 (H446/02 乙部)
Answer all questions. Focus on a major program design scenario requiring object-oriented coding, algorithm writing, and analysis.
9 題目 · 49 分
題目 1 · structured_oop_code
5 分
An eco-friendly delivery company uses an object-oriented fleet management system. Write the class definition for the base class DeliveryVehicle. The class must have: 1. Private attributes: vehicleID (string), maxPayload (real), and currentPayload (real). 2. A constructor (new) that accepts vehicleID and maxPayload as parameters and sets currentPayload to 0.0. 3. Public getter methods for all three attributes. 4. A public function loadPackage(weight) which adds weight to currentPayload and returns true if currentPayload does not exceed maxPayload, otherwise leaves currentPayload unchanged and returns false. Write your answer as a single-line block of OCR pseudocode (using spaces to separate statements).
查看答案詳解收起答案詳解
解題
The class DeliveryVehicle is declared with three private attributes: vehicleID, maxPayload, and currentPayload. The constructor initializes these fields, setting currentPayload to 0.0. Getter methods are provided to access the private fields. The loadPackage method checks if adding the weight would exceed maxPayload; if not, it updates currentPayload and returns true, otherwise it returns false.
評分準則
1 mark: Declaring class DeliveryVehicle with correct private attributes. 1 mark: Constructor correctly initialising attributes and setting currentPayload to 0.0. 1 mark: Implementation of all three getter methods returning correct attributes. 1 mark: loadPackage checking boundary condition correctly (currentPayload + weight <= maxPayload). 1 mark: loadPackage updating currentPayload and returning true/false correctly.
題目 2 · structured_oop_code
5 分
Write the class definition for the subclass Drone which inherits from DeliveryVehicle. The class must have: 1. Private attributes: maxAltitude (integer) and batteryLevel (real). 2. A constructor (new) that accepts vehicleID, maxPayload, and maxAltitude. It must call the parent constructor using vehicleID and maxPayload, set maxAltitude, and set batteryLevel to 100.0. 3. A public function flyTo(altitude) that returns true if altitude is less than or equal to maxAltitude and batteryLevel is strictly greater than 10.0, otherwise returns false. Write your answer as a single-line block of OCR pseudocode (using spaces to separate statements).
查看答案詳解收起答案詳解
解題
The class Drone is declared as inheriting from DeliveryVehicle. It contains the additional private attributes maxAltitude and batteryLevel. The constructor calls the superclass constructor first, then sets maxAltitude and batteryLevel. The flyTo method checks both the altitude limit and the battery threshold before returning true or false.
評分準則
1 mark: Class header showing correct inheritance (inherits DeliveryVehicle). 1 mark: Correct private attributes declared. 1 mark: Constructor correctly calling parent constructor with super.new(id, maxLoad). 1 mark: Constructor setting maxAltitude and batteryLevel to 100.0. 1 mark: flyTo function correctly implementing the compound boolean check and returning true/false.
題目 3 · structured_oop_code
5 分
Write the class definition for the subclass ElectricVan which inherits from DeliveryVehicle. The class must have: 1. Private attributes: hasDriver (boolean) and routeDestinations (an array of 10 strings). 2. A constructor (new) that accepts vehicleID and maxPayload. It must call the parent constructor, set hasDriver to true, and initialize all 10 elements of routeDestinations to empty strings (''). 3. A public function addDestination(town) which iterates through routeDestinations to find the first empty string element, updates that element to town, and returns true. If the array is full, it returns false. Write your answer as a single-line block of OCR pseudocode (using spaces to separate statements).
查看答案詳解收起答案詳解
解題
The subclass ElectricVan inherits from DeliveryVehicle. It initializes hasDriver to true and sets up a routeDestinations array of size 10 with empty strings. The addDestination method loops through the array, finding the first index where the value is empty, assigning the town, and returning true immediately. If the loop completes, it means the list is full, so it returns false.
評分準則
1 mark: Correct class header indicating inheritance and declaring private attributes. 1 mark: Constructor calling parent constructor with correct parameters. 1 mark: Initializing hasDriver to true and routeDestinations to an array of 10 empty strings. 1 mark: addDestination method using a loop (0 to 9) to check elements. 1 mark: Correctly setting element to town and returning true, or returning false if full.
題目 4 · structured_oop_code
5 分
The DeliveryVehicle class contains a method unloadAll() that resets currentPayload to 0.0 and returns the weight unloaded. The Drone subclass needs to override this method. In Drone, unloading cargo uses 5.0 percent of its batteryLevel (batteryLevel cannot drop below 0.0). Write the overridden unloadAll() method for the Drone subclass. The method must: 1. Reduce batteryLevel by 5.0 (ensuring it does not fall below 0.0). 2. Call the parent class's unloadAll() method to reset the payload and retrieve the unloaded weight. 3. Return the unloaded weight value. Write your answer as a single-line block of OCR pseudocode (using spaces to separate statements).
查看答案詳解收起答案詳解
解題
The overridden unloadAll() function first updates the subclass's batteryLevel attribute, preventing it from going below 0.0 using an if condition. It then calls the superclass method using super.unloadAll() to perform the standard unloading tasks and capture the weight, which it then returns.
評分準則
1 mark: Correct method signature inside Drone context. 1 mark: Correctly subtracting 5.0 from batteryLevel. 1 mark: Ensuring batteryLevel does not drop below 0.0. 1 mark: Correctly calling super.unloadAll() or parent.unloadAll(). 1 mark: Returning the value retrieved from the parent call.
題目 5 · structured_oop_code
5 分
A FleetManager class manages an array of 50 DeliveryVehicle objects called fleet (which may contain null elements). Write the method calculateTotalFreeCapacity() for the FleetManager class. The method must loop through the fleet array, ignore null elements, and calculate the total remaining payload capacity across all active vehicles (where remaining capacity is maxPayload minus currentPayload). The method must return the total remaining capacity. Assume the getter methods getMaxPayload() and getCurrentPayload() exist in DeliveryVehicle. Write your answer as a single-line block of OCR pseudocode (using spaces to separate statements).
查看答案詳解收起答案詳解
解題
The function initializes an accumulator totalFree to 0.0. It loops through indices 0 to 49 of the fleet array. It checks if fleet[i] is not null to avoid a null pointer error. For each active vehicle, it calculates the remaining capacity using its getter methods and adds this to totalFree. Finally, it returns the accumulated total.
評分準則
1 mark: Initialising total accumulation variable to 0.0. 1 mark: Loop correctly covering indices 0 to 49. 1 mark: Checking fleet[i] != null before accessing methods. 1 mark: Correctly calling getMaxPayload() and getCurrentPayload() and calculating the difference. 1 mark: Accumulating and returning the correct total.
題目 6 · structured_oop_code
5 分
Write the method findSuitableVehicle(weight) for the FleetManager class. The method must search the fleet array (ignoring null elements) to find the vehicle with the smallest remaining payload capacity that can still accommodate the given real value weight (a best-fit strategy). The method must return the index of this vehicle in the fleet array, or -1 if no vehicle can accommodate the weight. Assume getter methods getMaxPayload() and getCurrentPayload() are available. Write your answer as a single-line block of OCR pseudocode (using spaces to separate statements).
查看答案詳解收起答案詳解
解題
The findSuitableVehicle method initializes bestIndex to -1 and bestCapacity to a very large number (sentinel). It loops through the fleet array, ignoring null elements. For each active vehicle, it calculates its free capacity. If this free capacity can hold the weight (freeCap >= weight) and is smaller than the bestCapacity found so far, it updates bestCapacity and records the current index. It returns bestIndex at the end.
評分準則
1 mark: Initialising bestIndex to -1 and a bestCapacity variable to a large default value. 1 mark: Correct loop structure with null checks. 1 mark: Calculating free capacity and verifying if it is >= weight. 1 mark: Checking if the free capacity is strictly less than the currently recorded bestCapacity. 1 mark: Correctly updating tracking variables and returning the final index.
題目 7 · code_completion_and_debugging
5 分
An OOP implementation of a Binary Search Tree (BST) insertion algorithm is shown below. It contains two blanks ([ BLANK 1 ] and [ BLANK 2 ]) and two logic bugs (Bug A and Bug B).
class Node public data public left public right
public procedure new(newData) data = newData left = null right = null endprocedure endclass
class BinarySearchTree private root
public procedure new() root = null endprocedure
public procedure insert(newValue) if [ BLANK 1 ] then root = new Node(newValue) else insertNode(root, newValue) endif endprocedure
private procedure insertNode(currentNode, newValue) if newValue < currentNode.data then if [ BLANK 2 ] then currentNode.left = new Node(newValue) else insertNode(root, newValue) // Bug A endif else if currentNode.right != null then // Bug B currentNode.right = new Node(newValue) else insertNode(currentNode.right, newValue) endif endif endprocedure endclass
Analyze the code and answer the following: 1. State the code required to complete [ BLANK 1 ] and [ BLANK 2 ]. 2. Explain why the statement marked Bug A causes a logical failure and write the corrected statement. 3. Identify the logical correction needed for the line marked Bug B and explain its impact on the insertion algorithm.
查看答案詳解收起答案詳解
解題
1. - [ BLANK 1 ] must check if the tree is currently empty so the root can be initialized: root == null. - [ BLANK 2 ] must check if the current node does not have a left child before attaching the new child node: currentNode.left == null.
2. Bug A calls the recursive routine insertNode by passing the root of the BST instead of the left child (currentNode.left). This resets the traversal to the top of the tree, causing infinite recursion. The correct statement is: insertNode(currentNode.left, newValue).
3. Bug B check is inverted. By checking if the right child is NOT null (currentNode.right != null) before creating a new node, the code incorrectly overwrites the right child if it exists. If it does not exist, it runs the 'else' branch and tries to call insertNode on a null object, crashing the application. The comparison operator must be corrected to == null.
評分準則
1 mark: Completing [ BLANK 1 ] as root == null (or equivalent null check). 1 mark: Completing [ BLANK 2 ] as currentNode.left == null (or equivalent null check). 1 mark: Explaining that Bug A causes infinite recursion because the function repeatedly resets the search to the root. 1 mark: Correcting Bug A to insertNode(currentNode.left, newValue). 1 mark: Correcting Bug B to currentNode.right == null (or equivalent) and explaining that the original code overwrites existing nodes or causes a crash.
題目 8 · code_completion_and_debugging
5 分
The following pseudocode is an incomplete and buggy implementation of the Insertion Sort algorithm designed to sort an array of integers in ascending order. It contains three blanks ([ BLANK A ], [ BLANK B ], and [ BLANK C ]) and one logical bug (Bug 1).
procedure insertionSort(arr) for i = 1 to arr.length - 1 key = arr[i] j = [ BLANK A ] while j >= 0 and [ BLANK B ] arr[j + 1] = arr[j] j = j + 1 // Bug 1 endwhile [ BLANK C ] = key next i endprocedure
1. State the expressions required to complete [ BLANK A ], [ BLANK B ], and [ BLANK C ]. 2. Identify the logical bug in the line marked Bug 1, state the corrected line of code, and explain why this bug causes a runtime or logic error. 3. Explain what logical error would occur if the loop condition j >= 0 was changed to j > 0.
查看答案詳解收起答案詳解
解題
1. - [ BLANK A ] must initialize the index j to point to the element immediately before i: i - 1. - [ BLANK B ] must check if the element at index j is larger than the key value we are positioning, to trigger the shift: arr[j] > key. - [ BLANK C ] must assign the key value back to its final inserted position: arr[j + 1].
2. Bug 1: In insertion sort, we decrement j to traverse backwards through the sorted sub-array. Incrementing j (j = j + 1) will keep the loop running indefinitely or raise an Index Out of Bounds exception. The corrected line is: j = j - 1.
3. If the loop stops when j > 0, the element at index 0 (arr[0]) is never compared. This means if a new value is smaller than every sorted item, the shift stops early and the value is erroneously placed at index 1 instead of index 0.
評分準則
1 mark: Correctly completing [ BLANK A ] as i - 1. 1 mark: Correctly completing [ BLANK B ] as arr[j] > key. 1 mark: Correctly completing [ BLANK C ] as arr[j + 1]. 1 mark: Identifying and correcting Bug 1 to j = j - 1, explaining that incrementing j causes an infinite loop or index out of bounds error. 1 mark: Explaining that changing j >= 0 to j > 0 prevents the item at index 0 from being checked, resulting in an unsorted array if the key is the minimum element.
題目 9 · extended_essay
9 分
A software development company is designing a smart warehouse management system. The system needs to track different types of automated guided vehicles (AGVs): forklift AGVs and towing AGVs. Both AGV types share common properties (such as ID, current battery charge, and warehouse grid position) but have distinct behaviors (for example, a forklift AGV can lift pallets up to a certain height, while a towing AGV has a maximum pulling capacity).
The developers are deciding whether to implement this system using inheritance (where specific AGVs inherit from a base AGV class) or composition (where a generic AGV object contains independent components like a LiftComponent or a TowComponent).
Discuss the advantages and disadvantages of using inheritance versus composition for this system. Your response should address: - How polymorphism can be utilized in the inheritance approach when updating all AGVs. - The impact of both approaches on encapsulation and long-term code maintenance. - High-level OOP pseudocode demonstrating how either of the two approaches would define these objects and how a collection of them would be updated.
查看答案詳解收起答案詳解
解題
### Detailed Solution
#### 1. Inheritance vs. Composition Analysis * **Inheritance (IS-A relationship):** * `ForkliftAGV` and `TowingAGV` inherit from a base `AGV` class. * *Advantages:* Avoids code duplication for shared attributes (ID, battery charge, position). Easy to set up initially. * *Disadvantages:* Rigid hierarchy. If a hybrid AGV is created that can both lift and tow, multiple inheritance (which is not supported in many languages) or duplicate code is required. It also breaks encapsulation to some extent because subclasses are highly dependent on the base class implementation details (fragile base class problem). * **Composition (HAS-A relationship):** * A generic `AGV` class contains instances of behavior components (e.g., an optional `LiftAbility` reference and `TowAbility` reference). * *Advantages:* Exceptional flexibility. Behaviors can be added, removed, or changed at runtime. Stronger encapsulation as components are completely decoupled and self-contained. * *Disadvantages:* More complex design initially; requires writing delegate methods inside the container class to call component methods.
#### 2. Polymorphism * Polymorphism allows a collection (e.g., an array or list) of the base class type `AGV` to store instances of `ForkliftAGV` and `TowingAGV` seamlessly. * During the system update loop, the main program can iterate through the list and call `.update()` on each object. The program does not need to know the specific subclass type; the correct overridden method is resolved dynamically at runtime.
#### 3. High-Level OOP Pseudocode (Inheritance Approach Example) ``` class AGV private id private batteryCharge private position
public constructor(newId, startPos) id = newId batteryCharge = 100 position = startPos endconstructor
public procedure update() batteryCharge = batteryCharge - 1 endprocedure endclass
class ForkliftAGV inherits AGV private maxLiftHeight
public constructor(newId, startPos, height) super(newId, startPos) maxLiftHeight = height endconstructor
// Polymorphic Update Loop class WarehouseController private agvList = []
public procedure updateAll() for i = 0 to agvList.length - 1 agvList[i].update() next i endprocedure endclass ```
評分準則
This question is marked using a levels-of-response grid:
### Level 3 (7-9 Marks) * **Detailed & Accurate Comparison:** Detailed comparison of inheritance vs. composition in this scenario, referencing specific challenges (e.g., hybrid AGVs, fragile base class, dynamic behavior adjustment). * **Polymorphism & Encapsulation:** Clear explanation of how polymorphism allows a single collection to handle multiple AGV types, and how encapsulation is affected by both designs. * **Pseudocode:** Correct, logically sound pseudocode that defines a base/subclass or component structure, including a working update loop demonstrating polymorphism or composition delegation.
### Level 2 (4-6 Marks) * **Sound Comparison:** Sound understanding of both paradigms with some attempt to apply them to the AGV scenario. * **Polymorphism & Encapsulation:** Explanation of either polymorphism or encapsulation with minor omissions. * **Pseudocode:** Mostly correct pseudocode with minor syntax or logical errors, but showing the overall structural layout.
### Level 1 (1-3 Marks) * **Basic Understanding:** Identifies basic definitions of inheritance and/or composition but with limited comparison. * **Polymorphism & Encapsulation:** Lacks depth or contains significant errors regarding polymorphism/encapsulation. * **Pseudocode:** Incomplete, absent, or heavily flawed pseudocode.
想知道自己有幾分把握?
Thinka 是 DSE 學生用的 AI 練習應用程式,有無限量練習題、即時自動批改和詳細解題步驟。逾 100,000 名學生用它確認自己真的識,而不只是「以為識」。