An original Thinka practice paper modelled on the structure and difficulty of the Jun 2023 Cambridge OCR AS Level Computer Science - H046 paper. Not affiliated with or reproduced from Cambridge.
部分 H046/01 Computing Principles
Answer all questions. Calculators must not be used.
20 題目 · 64 分
題目 1 · Structured Short Answer
2.5 分
Describe the role of the Program Counter (PC) during the Fetch-Decode-Execute cycle and state how its value is updated during this process.
查看答案詳解收起答案詳解
解題
The Program Counter (PC) is a dedicated register in the CPU. Its primary purpose is to hold the memory address of the next instruction that needs to be fetched and executed. During the Fetch phase of the FDE cycle, the address stored in the PC is copied to the Memory Address Register (MAR) via the internal bus. Immediately after this copy operation occurs, the value of the PC is incremented by 1 (or by the size of the instruction) so that it is prepared for the subsequent cycle.
評分準則
1 mark: Stating that the PC holds the memory address of the next instruction to be fetched. 1 mark: Stating that the PC is incremented by 1 (or by the instruction size) during the Fetch phase. 0.5 marks: Stating that the increment happens immediately after copying the address to the Memory Address Register (MAR).
題目 2 · Structured Short Answer
2.5 分
Describe the fundamental difference between paging and segmentation as memory management techniques used by an operating system.
查看答案詳解收起答案詳解
解題
Paging is a physical memory management scheme where memory is divided into physical, fixed-sized blocks (pages). This division is uniform and does not align with the logical structures of the software. Segmentation, in contrast, is a logical memory management scheme where memory is split into variable-sized blocks (segments) that match the logical divisions of the program, such as functions, objects, or arrays.
評分準則
1 mark: Explaining that paging divides memory into physical, fixed-size blocks. 1 mark: Explaining that segmentation divides memory into logical, variable-size blocks. 0.5 marks: Connecting this to internal/external fragmentation (e.g., paging can suffer from internal fragmentation while segmentation can suffer from external fragmentation) or indicating that paging is invisible to the programmer whereas segmentation is not.
題目 3 · Structured Short Answer
2.5 分
Explain how a Domain Name System (DNS) server resolves a human-readable URL (such as \(www.example.com\)) into an IP address.
查看答案詳解收起答案詳解
解題
When a domain name is entered, the computer checks its local DNS cache first. If the record is missing, it queries a recursive DNS resolver. If the resolver does not have the record, it recursively queries a hierarchy of DNS servers (Root, Top-Level Domain like .com, and finally the Authoritative Name Server). Once the Authoritative server locates the IP address, it passes it back to the resolver and client to load the website.
評分準則
1 mark: Stating that the DNS server checks a database or local lookup table for the matching domain name. 1 mark: Explaining the referral process up the DNS hierarchy (e.g., root, TLD, authoritative servers) if the domain is not in the local cache. 0.5 marks: Stating that the IP address is returned to the client browser to allow a connection to be established.
題目 4 · Structured Short Answer
2.5 分
State one advantage of using an interpreter instead of a compiler during the development phase of a software application, and explain why this advantage exists.
查看答案詳解收起答案詳解
解題
An interpreter translates and executes source code line-by-line. This is highly advantageous during development because if a bug is encountered, the program stops running exactly at the line with the error. The programmer can immediately see the state of variables, fix the error, and resume testing. Unlike a compiler, there is no need to wait for a time-consuming build and compilation phase for the entire codebase after making a tiny adjustment.
評分準則
1 mark: Identifying a valid advantage (e.g., faster debugging, immediate error isolation, no recompilation wait time). 1 mark: Explaining the mechanism (the interpreter executes code line-by-line and halts execution instantly at the point of the error). 0.5 marks: Linking this mechanism back to saving development time or allowing rapid prototyping cycles.
題目 5 · Structured Short Answer
2.5 分
Convert the denary number \(-43\) into an 8-bit two's complement binary integer. Show your working.
查看答案詳解收起答案詳解
解題
To convert \(-43\) to 8-bit two's complement: 1. Find the 8-bit binary representation of the positive value (+43): 43 = 32 + 8 + 2 + 1, which in binary is 00101011. 2. Invert (flip) all the bits (one's complement): 00101011 becomes 11010100. 3. Add 1 to the result of the inversion: 11010100 + 1 = 11010101. Therefore, the 8-bit representation of \(-43\) is 11010101.
評分準則
1 mark: Correctly converting positive 43 into 8-bit binary (00101011). 1 mark: Correctly applying the two's complement process (either inverting the bits of positive 43 to get 11010100 and adding 1, or subtracting 43 from 256). 0.5 marks: Correct final binary representation (11010101).
題目 6 · Structured Short Answer
2.5 分
Explain why a Solid-State Drive (SSD) is more suitable than a Magnetic Hard Disk Drive (HDD) for a high-performance portable laptop.
查看答案詳解收起答案詳解
解題
SSDs use flash memory chips rather than spinning magnetic platters. Because there are no moving parts, SSDs are not prone to mechanical damage or read/write errors caused by physical movement, vibrations, or drops—which are common hazards for a portable laptop. Furthermore, SSDs provide significantly lower latency and faster data transfer rates, while consuming less energy, directly improving battery life.
評分準則
1 mark: Explaining that SSDs have no moving parts, making them physically robust/durable against drops or impact. 1 mark: Explaining that SSDs have higher read/write performance (faster boot times) or lower power usage. 0.5 marks: Explicitly linking these points back to the user context of a portable laptop (e.g., maintaining data integrity on the move, or maximizing battery longevity).
題目 7 · Structured Short Answer
2.5 分
Simplify the Boolean expression \(\neg(P \land \neg Q)\) using De Morgan's laws. Show your working.
查看答案詳解收起答案詳解
解題
We apply De Morgan's Law, which states that \(\neg(A \land B) = \neg A \lor \neg B\). Substituting \(A = P\) and \(B = \neg Q\): \(\neg(P \land \neg Q) = \neg P \lor \neg(\neg Q)\). Using the double negation rule, \(\neg(\neg Q)\) simplifies to \(Q\). This leaves the final simplified expression as: \(\neg P \lor Q\).
評分準則
1 mark: Correctly applying De Morgan's Law to distribute the negation and change the operator to OR, resulting in \(\neg P \lor eg(\neg Q)\). 1 mark: Applying the double negation rule to simplify \(\neg(\neg Q)\) to \(Q\). 0.5 marks: Stating the correct final simplified expression \(\neg P \lor Q\).
題目 8 · Structured Short Answer
2.5 分
A queue is implemented as a circular queue of size \(N\) using an array. Explain how the rear pointer is updated when an element is successfully enqueued.
查看答案詳解收起答案詳解
解題
In a circular queue of fixed size \(N\), memory is reused by allowing pointers to wrap around to the beginning of the array. When an item is enqueued, the pointer is updated using the modulo operator: \(\text{rear} = (\text{rear} + 1) \pmod N\). This calculation increments the index by 1, but if the incremented index equals \(N\) (the size of the array), it wraps back to 0, ensuring that empty spaces at the start of the array can be refilled.
評分準則
1 mark: Stating that the rear pointer is incremented (by 1). 1 mark: Describing the use of modulo arithmetic (or MOD operator) with the queue size \(N\) to facilitate the pointer wrap-around. 0.5 marks: Stating that this wrap-around to index 0 occurs when the pointer exceeds the highest index of the array, provided the queue is not full.
題目 9 · Structured Short Answer
2.5 分
Define what is meant by a "foreign key" and explain how it is used to establish a relationship between two tables in a relational database.
查看答案詳解收起答案詳解
解題
A foreign key is a field (or collection of fields) in one table that uniquely identifies a row in another table by referencing that table's primary key. This establishes a logical relationship (typically one-to-many) between the tables. It maintains referential integrity by ensuring that any value in the foreign key column must already exist in the primary key column of the related table.
評分準則
- 1 mark: Defining a foreign key as an attribute in a table that refers to/is the primary key of another table. - 1 mark: Explaining its role in linking/establishing a relationship between two tables. - 0.5 marks: Correctly mentioning that it maintains or enforces referential integrity.
題目 10 · Structured Short Answer
2.5 分
Explain the primary differences between how a network switch and a network router direct data packets.
查看答案詳解收起答案詳解
解題
A switch operates within a local area network (LAN) and uses MAC (Media Access Control) addresses to forward data frames directly to the specific destination port of connected devices. A router operates at the boundary between different networks (such as connecting a LAN to the Internet) and uses IP (Internet Protocol) addresses to determine the best path and forward data packets across different networks.
評分準則
- 1 mark: Explaining that a switch works within a single network (LAN) and/or uses MAC addresses. - 1 mark: Explaining that a router works between different networks (e.g., WAN/LAN) and/or uses IP addresses. - 0.5 marks: Clearly contrasting the two in terms of local frame delivery versus global packet routing.
題目 11 · Structured Short Answer
2.5 分
Describe how paging is used by an operating system to manage memory, and state one potential disadvantage of paging.
查看答案詳解收起答案詳解
解題
Paging is a physical memory management technique where physical memory is divided into fixed-size blocks called page frames, and logical memory is divided into blocks of the same size called pages. The operating system uses a page table to map logical pages to physical frames in RAM. A key disadvantage is 'disk thrashing', which occurs when pages are constantly being swapped between physical RAM and virtual memory on secondary storage, severely reducing system performance.
評分準則
- 1 mark: Describing that physical and logical memory are divided into fixed-size blocks (pages and frames). - 1 mark: Describing the use of a mapping table (page table) to translate logical pages to physical locations. - 0.5 marks: Identifying a valid disadvantage (e.g., disk thrashing, performance overhead of maintaining page tables, or internal fragmentation).
題目 12 · Structured Short Answer
2.5 分
Describe the sequence of actions involving the Program Counter (PC) during the Fetch stage of the Fetch-Decode-Execute cycle.
查看答案詳解收起答案詳解
解題
At the start of the Fetch stage, the Program Counter (PC) holds the memory address of the next instruction to be fetched. This address is copied from the PC to the Memory Address Register (MAR). The PC is then immediately incremented (by 1) to point to the memory address of the next sequential instruction, preparing it for the subsequent cycle.
評分準則
- 1 mark: Identifying that the PC holds the address of the next instruction to be executed. - 1 mark: Describing that this address is copied from the PC to the Memory Address Register (MAR). - 0.5 marks: Explaining that the PC is then incremented to point to the next sequential instruction.
題目 13 · Structured Short Answer
2.5 分
Compare solid-state flash storage with magnetic hard disk storage by stating two advantages of flash storage, and describing one specific scenario where magnetic storage is still preferred.
查看答案詳解收起答案詳解
解題
Solid-state flash storage contains no moving parts, making it highly durable and shock-resistant, and it offers much faster read/write access speeds than magnetic storage. However, magnetic hard disk storage is still preferred for bulk/long-term high-capacity data archives or server backup drives because it offers a significantly lower cost-per-gigabyte for high volumes of data.
評分準則
- 1 mark: Stating one advantage of flash storage (e.g., faster read/write/access speeds, lower power consumption, silent operation). - 1 mark: Stating a second distinct advantage of flash storage (e.g., high durability/shock resistance due to no moving parts, smaller physical size). - 0.5 marks: Providing a valid scenario for magnetic storage preference (e.g., high-capacity servers, bulk data archiving/backups where cost-per-gigabyte is key).
題目 14 · Structured Short Answer
2.5 分
Convert the 8-bit two's complement binary integer \(10110101_2\) to its denary equivalent. Show your working.
查看答案詳解收起答案詳解
解題
The binary integer is \(10110101_2\). Using two's complement, the place values for 8 bits are: \(-128, 64, 32, 16, 8, 4, 2, 1\). Using the bits from left to right: \(1 \times (-128) + 0 \times 64 + 1 \times 32 + 1 \times 16 + 0 \times 8 + 1 \times 4 + 0 \times 2 + 1 \times 1\) \(= -128 + 32 + 16 + 4 + 1\) \(= -128 + 53\) \(= -75\).
Alternatively, to find the absolute value, flip the bits of the positive counterpart: Inverting \(10110101\) gives \(01001010\). Adding 1 gives \(01001011_2\), which is \(64 + 8 + 2 + 1 = 75_10\). Therefore, the original number is \(-75\).
評分準則
- 1 mark: Demonstrating understanding of the negative weight of the MSB (i.e., identifying it as \(-128\)) OR demonstrating correct binary negation steps (flipping bits and adding 1). - 1 mark: Showing a correct intermediate addition/summation step (e.g., \(-128 + 53\) or \(64 + 8 + 2 + 1 = 75\)). - 0.5 marks: Stating the correct final answer of \(-75\).
題目 15 · Structured Short Answer
2.5 分
State the difference in purpose between HTML and CSS in web development, and explain how an external CSS stylesheet is linked to an HTML document.
查看答案詳解收起答案詳解
解題
HTML (HyperText Markup Language) is used to define the actual content and semantic structure of a web page (such as headings, paragraphs, and links). CSS (Cascading Style Sheets) is used to control the visual presentation, styling, and layout of that content (such as colors, fonts, and positioning). An external CSS stylesheet is linked to an HTML document using the `` tag within the `` block of the HTML file.
評分準則
- 1 mark: Correctly explaining the purpose of HTML (structure/content). - 1 mark: Correctly explaining the purpose of CSS (styling/presentation/layout). - 0.5 marks: Identifying that linking is done using the `` tag within the `` section of the HTML document.
題目 16 · Structured Short Answer
2.5 分
Using Boolean algebra laws, simplify the expression \(A \cdot (A + B) + A \cdot \bar{B}\) to its simplest form. Show your working.
查看答案詳解收起答案詳解
解題
Let's simplify \(A \cdot (A + B) + A \cdot \bar{B}\):
**Method 1: Expansion** 1. Expand using the distributive law: \(A \cdot A + A \cdot B + A \cdot \bar{B}\) 2. Apply the idempotent law \(A \cdot A = A\): \(A + A \cdot B + A \cdot \bar{B}\) 3. Factor out \(A\) from the last two terms: \(A + A \cdot (B + \bar{B})\) 4. Apply the complement law \(B + \bar{B} = 1\): \(A + A \cdot (1)\) 5. This simplifies to \(A + A\), which by the idempotent law is simply \(A\).
**Method 2: Absorption Law** 1. Apply the absorption law \(A \cdot (A + B) = A\) to the first term: \(A + A \cdot \bar{B}\) 2. Apply the absorption law again to the result: \(A + A \cdot \bar{B} = A\).
評分準則
- 1 mark: Applying initial simplification rules correctly (e.g., expanding the expression to \(A \cdot A + A \cdot B + A \cdot \bar{B}\) or using the absorption law to reduce the first part to \(A\)). - 1 mark: Showing a valid intermediate simplification step (e.g., showing \(A(B + \bar{B}) = A\) or arriving at \(A + A \cdot \bar{B}\)). - 0.5 marks: Correctly identifying the final simplified expression as \(A\).
題目 17 · Structured Short Answer
3 分
During the compilation of a computer program, the source code is analysed. Describe three tasks that are performed during the lexical analysis stage of compilation.
查看答案詳解收起答案詳解
解題
During lexical analysis, the compiler performs several key tasks: 1. It removes unnecessary characters such as whitespace, tabs, and comments. 2. It analyses groups of characters to identify lexemes and replaces them with corresponding tokens (e.g., keywords, operators, constants). 3. It builds the symbol table, entering identifiers and preparing details like scope and type.
評分準則
Award 1 mark per valid point, up to a maximum of 3 marks: - Whitespace, tabs, and comments are removed (1 mark). - Keywords, identifiers, and constants are replaced by tokens (1 mark). - Identifiers are added to the symbol table (1 mark). - Basic syntax check on lexemes is performed / checks for illegal identifiers (1 mark).
題目 18 · Structured Short Answer
3 分
The system bus in a computer consists of three separate buses: the data bus, the address bus, and the control bus. Describe the specific purpose of the address bus and the data bus, explaining how their direction of data flow differs.
查看答案詳解收起答案詳解
解題
The address bus is used to transmit the memory address of the instruction or data currently being read from or written to. This bus is unidirectional, meaning signals only travel from the processor to the memory/input-output controllers. In contrast, the data bus transmits the actual data or instructions between the CPU, memory, and input/output devices. This bus is bidirectional, allowing data to flow both into and out of the CPU.
評分準則
Award up to 3 marks: - Purpose of address bus: Carries the memory address of the location being accessed (1 mark). - Purpose of data bus: Carries the actual data/instructions being transferred (1 mark). - Comparison of direction: The address bus is unidirectional (CPU to memory) whereas the data bus is bidirectional (1 mark).
題目 19 · Discuss
9 分
A national chain of clothing retailers is planning to implement an AI-based surveillance system across all of its stores. This system uses facial recognition to identify individuals who are on a national shoplifting database and alerts security staff immediately. Additionally, the system analyzes shoppers' movements, approximate ages, and facial expressions to evaluate their reactions to store displays.
Discuss the ethical, moral, and cultural issues associated with the implementation of this system.
查看答案詳解收起答案詳解
解題
Ethical Issues: 1. Consent and Privacy: Shoppers entering the store are subjected to facial scans without explicit informed consent. Opting out is functionally impossible for physical retail shopping. 2. Data Security: Biometric data is uniquely sensitive. If stored centrally, it represents a high-value target for hackers, with the risk of identity theft or profiling if data is leaked.
Moral Issues: 1. Algorithmic Bias: Facial recognition models have higher error rates for women and ethnic minorities. This can cause false positives, leading to discriminatory treatment and wrongful confrontation by security staff. 2. Lack of Human Discretion: Over-reliance on automated systems can lead to a culture where security personnel trust 'the computer' over physical evidence or human empathy.
Cultural Issues: 1. Normalization of Surveillance: Implementing such systems in routine daily spaces like clothing stores contributes to the public accepting invasive tracking as a normal part of life, reducing expectations of privacy. 2. Deterrence and Trust: Knowing they are continuously watched and their expressions analyzed might alienate customers, creating an atmosphere of suspicion and changing the natural shopping behavior of individuals.
評分準則
Level of Response Framework:
Level 3 (7-9 marks): - Demonstrates comprehensive knowledge of ethical, moral, and cultural aspects of the technology. - Discussion is balanced, clear, and highly specific to both the shoplifting database and marketing analysis aspects. - Uses relevant computer science terminology accurately.
Level 2 (4-6 marks): - Shows sound knowledge of some aspects, but the discussion may be unbalanced (e.g., focusing heavily on privacy and omitting cultural aspects). - The response is linked to the scenario but might be general in places.
Level 1 (1-3 marks): - Demonstrates limited knowledge with generic assertions (e.g., 'hacking is bad'). - Unstructured response with little to no application to the scenario.
Key Points to credit: - Ethical: Privacy rights, general lack of consent, risk of unauthorized access to database. - Moral: Algorithmic bias and false-positive impacts on minority groups, lack of redress. - Cultural: Changing expectations of public space, surveillance culture, anxiety/mistrust in retail.
題目 20 · Discuss
9 分
A small local medical practice with 15 staff members is setting up a new IT network. The practice must store highly sensitive patient medical records and billing information, which must be accessed by doctors, nurses, and receptionists. The practice manager is considering whether to implement a client-server network or a peer-to-peer network.
Discuss the advantages and disadvantages of both network architectures in this scenario, and recommend which option the medical practice should choose.
查看答案詳解收起答案詳解
解題
Client-Server Architecture: - Advantages: Centralized security (user permissions can be managed centrally to ensure only authorized personnel access patient records), centralized automated backups (protects against data loss on a single node), and centralized software administration. - Disadvantages: Single point of failure (if the server goes down, the entire medical practice loses access to records), and higher initial setup and ongoing support costs.
Peer-to-Peer Architecture: - Advantages: Lower setup cost (no dedicated server needed), simple to configure, and resilient (the failure of one workstation does not affect others). - Disadvantages: Decentralized security (difficult to enforce strict, uniform security measures on 15 separate machines), decentralized backups (reliance on individual users to back up data, risking loss of medical files), and performance degradation when machines host files accessed by other users.
Recommendation: - The medical practice must choose a client-server network. Because patient medical data is highly confidential and subject to regulatory protections, decentralized security and manual backups of a peer-to-peer network represent an unacceptable risk of data loss and privacy breach.
評分準則
Level of Response Framework:
Level 3 (7-9 marks): - Balanced, high-quality discussion of both architectures with clear links to the scenario (15 users, sensitive records). - Explicit, logical recommendation based on security and backup needs, with excellent use of network terminology.
Level 2 (4-6 marks): - Competent discussion of both network styles, listing standard advantages and disadvantages. - Some effort to link to the medical practice scenario, with a basic recommendation that may lack robust justification.
Level 1 (1-3 marks): - Descriptive account of the architectures with limited comparison. - Little or no application to the scenario; recommendation is absent or lacks any justification.
Key Points to credit: - Client-Server: Domain controller, file-level access rights, single backup schedule, higher cost, single point of failure. - Peer-to-Peer: Workgroups, resources shared directly, difficult to manage passwords/rights across 15 machines, individual machine failures do not stop the network. - Medical practice context: Security compliance, reliability, and data backup are non-negotiable, rendering peer-to-peer inadequate.
部分 H046/02 Algorithms and problem solving
Answer all questions. Write your solutions using pseudocode or program code.
17 題目 · 60.20000000000001 分
題目 1 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode function named hasDuplicates that takes a 1D array of integers named arr as a parameter. The function must return True if any element in the array appears more than once, and False otherwise. You may assume the length of the array can be obtained using length(arr).
查看答案詳解收起答案詳解
解題
The algorithm uses nested loops to compare each element with every subsequent element in the array. If a match is found, it immediately returns True. If the loops complete without finding a duplicate, it returns False.
評分準則
1 mark: Correct outer loop structure up to length(arr) - 2. 1 mark: Correct inner loop structure starting from i + 1 to length(arr) - 1. 1.2 marks: Correct comparison logic and appropriate return statements.
題目 2 · Structured Algorithmic Tasks
3.2 分
A linked list is stored in two 1-dimensional arrays: data and nextPointer. The index of the first element is stored in startPointer. Write a pseudocode procedure printList(data, nextPointer, startPointer) that traverses the list starting from startPointer and outputs each data value. The nextPointer array stores -1 to represent a null pointer.
查看答案詳解收起答案詳解
解題
Initialize a pointer variable 'current' with 'startPointer'. Loop while 'current' is not equal to -1. Inside the loop, print the element at index 'current' from the 'data' array, and update 'current' to the value of nextPointer[current].
評分準則
1 mark: Correctly initializing a pointer variable to startPointer and implementing a while loop checking for -1. 1 mark: Printing the current data element correctly inside the loop. 1.2 marks: Correctly updating the pointer using the nextPointer array inside the loop.
題目 3 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode algorithm for a Bubble Sort to sort a 1-dimensional array of numbers named values in ascending order. The length of the array is given by length(values).
查看答案詳解收起答案詳解
解題
Bubble sort iterates through the array multiple times. In each pass, adjacent elements are compared and swapped if they are in the wrong order. An outer loop runs n times, and an inner loop runs to compare elements, reducing the range of comparison each time as the largest elements bubble to the end.
評分準則
1 mark: Correct implementation of nested loops to iterate through the array. 1.2 marks: Correct conditional comparison (values[j] > values[j+1]) to sort in ascending order. 1 mark: Correct swap mechanism using a temporary variable.
題目 4 · Structured Algorithmic Tasks
3.2 分
A recursive function is defined as follows: function calculate(n) if n <= 1 then return 1 else return n * calculate(n - 2) endif endfunction. Show the step-by-step recursive calls and calculate the final return value when the function is called with \(calculate(7)\).
查看答案詳解收起答案詳解
解題
The function is called recursively decrementing n by 2 each time. \(calculate(7) = 7 \times calculate(5) = 7 \times 5 \times calculate(3) = 7 \times 5 \times 3 \times calculate(1) = 7 \times 5 \times 3 \times 1 = 105\).
評分準則
1 mark: Clearly showing the sequence of recursive calls (7, 5, 3, 1). 1 mark: Correctly identifying the base case condition and return value of 1. 1.2 marks: Correct mathematical resolution resulting in the final answer of 105.
題目 5 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode function getPostageCost(weight, thickness) that returns the cost of shipping based on the following rules: if weight is 100g or less and thickness is 5mm or less, the cost is 0.75; if weight is 100g or less and thickness is greater than 5mm, the cost is 1.20; for any weight greater than 100g, the cost is 2.00.
查看答案詳解收起答案詳解
解題
Using nested selection, first check if weight is less than or equal to 100. If yes, check if thickness is less than or equal to 5 and return 0.75, otherwise return 1.20. If weight is greater than 100, return 2.00.
評分準則
1 mark: Correctly checking weight <= 100 and nesting the thickness check inside. 1.2 marks: Correctly matching the conditions to the costs 0.75, 1.20, and 2.00. 1 mark: Returning 2.00 for any weight > 100.
題目 6 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode function convertMinutes(totalMinutes) that takes an integer totalMinutes and returns a string in the format 'X hours and Y minutes'. You must use DIV (integer division) and MOD (modulo) operators.
查看答案詳解收起答案詳解
解題
Use totalMinutes DIV 60 to calculate the number of full hours. Use totalMinutes MOD 60 to find the remaining minutes. Concatenate these values into the specified string format and return the result.
評分準則
1 mark: Using DIV operator correctly to determine hours. 1 mark: Using MOD operator correctly to determine remaining minutes. 1.2 marks: Constructing and returning the output string in the correct format.
題目 7 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode function findMin2D(grid) that accepts a 2-dimensional array of integers named grid (with 4 rows and 4 columns, indexed from 0 to 3) and returns the smallest value in the grid.
查看答案詳解收起答案詳解
解題
Initialize a minimum variable (minVal) to the first element grid[0][0]. Use nested loops to iterate through every row and column. Compare each cell to minVal and update minVal if a smaller number is found. Finally, return minVal.
評分準則
1 mark: Initializing the search variable with a valid grid element (e.g. grid[0][0]). 1 mark: Correct nested loop bounds (0 to 3 for both dimensions). 1.2 marks: Correct comparison condition and updating the minimum variable.
題目 8 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode function validatePassword(password) that returns True if the password string is valid, and False otherwise. A password is valid if it has a length of at least 8 characters and contains at least one exclamation mark ('!'). You may use length(password) and mid(password, index, 1) or individual character indexing.
查看答案詳解收起答案詳解
解題
First, check if the password's length is less than 8; if so, return False. Then, iterate through the string character by character to see if '!' is present. Return True if found, otherwise False.
評分準則
1 mark: Validation check for length(password) >= 8. 1.2 marks: Loop logic checking for the presence of '!' character. 1 mark: Correct combined boolean returns based on both conditions.
題目 9 · Structured Algorithmic Tasks
3.2 分
A programmer needs to search a 2D integer array `grid` of size 4 rows by 4 columns for a target value. Write a pseudocode function `findValue(grid, target)` that returns the coordinates of the target as a string in the format "row,col" (e.g. "2,3"). If the target is not found, the function should return "NOT FOUND".
查看答案詳解收起答案詳解
解題
To search a 2D array, we use nested loops. The outer loop iterates through the rows (0 to 3), and the inner loop iterates through the columns (0 to 3). During each iteration, the element at `grid[r, c]` is compared to the `target`. If a match is found, the row and column indices are converted and concatenated into a string separated by a comma and returned immediately. If both loops finish without finding the target, the function returns "NOT FOUND".
``` function findValue(grid, target) for r = 0 to 3 for c = 0 to 3 if grid[r, c] == target then return r + "," + c endif next c next r return "NOT FOUND" endfunction ```
評分準則
- 1 mark: Outer loop scanning all rows (0 to 3). - 1 mark: Inner loop scanning all columns (0 to 3). - 1.2 marks: Correct condition checking grid against target, returning correctly concatenated row and column coordinates, and a fallback return of "NOT FOUND".
題目 10 · Structured Algorithmic Tasks
3.2 分
A circular queue is implemented using a 1D array `queue` of size 5 (indices 0 to 4), with pointer variables `head`, `tail`, and an integer `size` (representing the current number of elements). Write a pseudocode procedure `enqueue(item)` to add an element to the queue. Assume error checking for a full queue is required, and should display "Queue Full" if no space is available.
查看答案詳解收起答案詳解
解題
Before adding an element, we must check if the queue is full by comparing `size` to 5. If it is full, an error is printed. Otherwise, we calculate the next position for `tail` using modular arithmetic: `tail = (tail + 1) MOD 5`. We then place the item at `queue[tail]` and increment the `size` counter by 1.
``` procedure enqueue(item) if size == 5 then print "Queue Full" else tail = (tail + 1) MOD 5 queue[tail] = item size = size + 1 endif endprocedure ```
評分準則
- 1 mark: Check if queue is full using `size == 5` and outputting an error. - 1 mark: Use modular arithmetic to update the tail pointer (`(tail + 1) MOD 5`). - 1.2 marks: Store the item in the array at index `tail` and correctly increment the `size` variable.
題目 11 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode function `isValidPassword(password)` that validates a password. The function must return `true` if the password has a length of at least 8 characters AND contains at least one digit character ('0'-'9'). Otherwise, it must return `false`. Assume you can use a helper function `isDigit(char)` which returns `true` if a character is a numeric digit.
查看答案詳解收起答案詳解
解題
The function first checks if the length of the string is less than 8. If so, it immediately returns `false`. If the length is valid, a loop traverses each character in the string. If the helper function `isDigit` returns `true` for any character, the function returns `true`. If the loop completes without finding any digits, the function returns `false`.
``` function isValidPassword(password) if length(password) < 8 then return false endif for i = 0 to length(password) - 1 if isDigit(password[i]) then return true endif next i return false endfunction ```
評分準則
- 1 mark: Initial check for length of password being at least 8 characters. - 1 mark: Loop that correctly iterates through each character index of the password string. - 1.2 marks: Conditional structure utilizing `isDigit` that returns `true` early on finding a digit, and returns `false` if the end of the loop is reached without success.
題目 12 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode procedure `bubblePass(arr, n)` that performs exactly one complete pass of a standard Bubble Sort algorithm on a 1D array `arr` of size `n` (indices 0 to `n-1`). The pass should compare adjacent elements and swap them if they are in the wrong order, bubbling the largest element to the end.
查看答案詳解收起答案詳解
解題
To complete a single pass of Bubble Sort, we iterate through the array from index `0` up to `n-2` so that we can compare `arr[i]` with `arr[i+1]` without going out of bounds. If `arr[i]` is strictly greater than `arr[i+1]`, we swap their values using a temporary variable `temp`.
``` procedure bubblePass(arr, n) for i = 0 to n - 2 if arr[i] > arr[i+1] then temp = arr[i] arr[i] = arr[i+1] arr[i+1] = temp endif next i endprocedure ```
評分準則
- 1 mark: Correct loop bounds from index 0 to `n-2` (or equivalent loop ending before out-of-bounds index). - 1 mark: Correct comparison condition checking if adjacent elements are in the wrong order (`arr[i] > arr[i+1]`). - 1.2 marks: Implementation of a swap mechanism using a third temporary variable to exchange values.
題目 13 · Structured Algorithmic Tasks
3.2 分
Write a pseudocode function `calculateAverage(total, count)` that computes the average of a total value over a specified count. It must enforce the precondition that `count` must be strictly greater than 0. If this precondition is violated, the function must output an error message "Error: Count must be greater than 0" and return a default value of `-1.0`. Otherwise, it returns the calculated average.
查看答案詳解收起答案詳解
解題
In defensive programming, checking preconditions helps prevent run-time errors like division by zero. If `count` is less than or equal to 0, the check triggers, outputs the error message, and returns the defined safe error value (`-1.0`). If valid, division is performed safely.
``` function calculateAverage(total, count) if count <= 0 then print "Error: Count must be greater than 0" return -1.0 else return total / count endif endfunction ```
評分準則
- 1 mark: Condition checking if `count` is less than or equal to 0 (precondition violation). - 1 mark: Printing the requested error message and returning `-1.0` if invalid. - 1.2 marks: Correctly calculating and returning `total / count` when the precondition is met.
題目 14 · Structured Algorithmic Tasks
3.2 分
Write a recursive pseudocode function `power(base, exponent)` that calculates and returns the value of \( \text{base}^{\text{exponent}} \). You may assume that `exponent` is a non-negative integer. Your solution must use recursion.
查看答案詳解收起答案詳解
解題
A recursive implementation of exponentiation depends on a base case and a recursive step. The base case is when `exponent` is equal to 0, which returns 1 (since \( x^0 = 1 \)). The recursive step returns `base` multiplied by the result of the function called with the `exponent` reduced by 1.
``` function power(base, exponent) if exponent == 0 then return 1 else return base * power(base, exponent - 1) endif endfunction ```
評分準則
- 1 mark: Base case checking if `exponent == 0` and returning 1. - 1 mark: Recursive step correctly calling `power(base, exponent - 1)`. - 1.2 marks: Correct overall expression returning `base * power(...)` and matching recursive functional structure.
題目 15 · Structured Algorithmic Tasks
3.2 分
In a binary search algorithm, a sorted 1D array `arr` is searched for a target value. Write the conditional structure of the binary search loop in pseudocode. Given the variables `low`, `high`, and `mid` (where `mid = INT((low + high) / 2)`), write code to compare `arr[mid]` with `target` and update either `low` or `high` appropriately, or indicate that the target has been found by returning `mid`.
查看答案詳解收起答案詳解
解題
Within a binary search loop, we check three possibilities: 1. If `arr[mid]` is equal to the target, the index `mid` is returned. 2. If `arr[mid]` is greater than the target, the search space must be restricted to the lower half by shifting `high` to `mid - 1`. 3. If `arr[mid]` is less than the target, the search space must be restricted to the upper half by shifting `low` to `mid + 1`.
``` if arr[mid] == target then return mid elseif arr[mid] > target then high = mid - 1 else low = mid + 1 endif ```
評分準則
- 1 mark: Check for equality returning `mid` if the target is found. - 1 mark: Shift the `high` pointer to `mid - 1` if `arr[mid] > target`. - 1.2 marks: Shift the `low` pointer to `mid + 1` if `arr[mid] < target` (handling the final case correctly with proper logic structure).
題目 16 · Structured Algorithmic Tasks
3.2 分
A node in a linked list is represented by an object with properties `value` and `next` (where `next` is a reference to the next node, or `null` if it is the end of the list). Write a pseudocode procedure `printList(startNode)` that traverses the linked list starting from `startNode` and outputs the `value` of each node.
查看答案詳解收起答案詳解
解題
To traverse a linked list, we initialize a temporary pointer/variable `current` to point to the `startNode`. We loop while `current` is not `null` (which represents the end of the list). Inside the loop, we print `current.value`, and then advance the pointer to the next node by setting `current = current.next`.
``` procedure printList(startNode) current = startNode while current != null print current.value current = current.next endwhile endprocedure ```
評分準則
- 1 mark: Initializing a tracker pointer (e.g., `current`) to the parameter `startNode`. - 1 mark: Loop that terminates when the tracker pointer becomes `null` (or equivalent sentinel check). - 1.2 marks: Outputting the current node's value and advancing the tracker pointer using `current = current.next`.
題目 17 · Extended Comparison/Writing
9 分
A software developer is choosing a sorting algorithm to organize a small array of real-time sensor readings that are collected at regular intervals. Because the readings are sampled frequently, the array is typically already sorted or very close to being sorted, but occasionally a new reading needs to be integrated.
Compare the suitability of the Bubble Sort and Insertion Sort algorithms for this specific application.
Your response should analyze: - How each algorithm operates. - Their respective time complexities in best, average, and worst cases. - Why one of these algorithms is more appropriate than the other for the developer’s specific scenario.
查看答案詳解收起答案詳解
解題
### 1. Operation of the Algorithms - **Bubble Sort:** Works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. This process is repeated for multiple passes until a full pass is completed with zero swaps, indicating the list is sorted. - **Insertion Sort:** Iterates through the list, building a sorted sublist at the beginning. It takes the next unsorted element and inserts it into its correct position within the sorted sublist by shifting larger elements to the right.
### 2. Time Complexities - **Bubble Sort:** - Best Case: O(n) (requires an optimized version with a swap flag that terminates if a pass completes with no swaps). - Average Case: O(n^2). - Worst Case: O(n^2) (when the list is in reverse order). - **Insertion Sort:** - Best Case: O(n) (when the list is already sorted, only one comparison is made per element and no shifts are required). - Average Case: O(n^2). - Worst Case: O(n^2) (when the list is in reverse order).
### 3. Scenario Suitability Comparison - The scenario describes a dataset that is "typically already sorted or very close to being sorted, but occasionally a new reading needs to be integrated." - For a nearly-sorted list, **Insertion Sort** is highly efficient. When a new reading is added, it only needs to make a few comparisons and a minimal number of shifts to place it in the correct position. Its performance under these conditions approaches O(n). - While an optimized **Bubble Sort** can achieve O(n) if the list is perfectly sorted, it is highly inefficient if even a single element is significantly out of position (especially a small element at the end of the list, known as a 'turtle'), as it requires many complete passes to bubble it to the beginning. - Therefore, **Insertion Sort** is the superior choice for this specific application due to its natural efficiency with almost-sorted data and lower overhead.
評分準則
This question is marked using a level of response grid:
**Level 3 (7-9 marks):** - Demonstrates a clear, coherent, and detailed understanding of both algorithms' mechanics. - Correctly identifies and compares the best, average, and worst-case time complexities using Big O notation for both algorithms. - Provides a well-reasoned and technically sound justification of why Insertion Sort is superior to Bubble Sort for nearly-sorted datasets. - Accurate use of computer science terminology throughout.
**Level 2 (4-6 marks):** - Explains the operation of both algorithms, though one explanation may be slightly clearer or more accurate than the other. - Identifies some of the correct time complexities (at least the worst-case for both). - Attempts to compare the algorithms within the context of the scenario, but the justification may lack depth or miss key mechanical differences (e.g., the impact of 'turtles' or shifting vs. swapping).
**Level 1 (1-3 marks):** - Explains the operation of at least one algorithm with basic accuracy. - May confuse the time complexities or state them incorrectly. - Offers little to no valid justification relating back to the developer's scenario.
**Indicative Content to look for:** - Bubble Sort compares adjacent pairs and swaps them; repeat passes until sorted. - Insertion Sort splits the list into sorted/unsorted partitions; inserts unsorted elements into their correct position by shifting. - Best-case complexity of O(n) for both (requires optimized bubble sort explanation). - Worst-case and Average-case of O(n^2) for both. - Insertion sort is much faster for inserting a single out-of-order element (nearly-sorted data) because it only requires localized shifting, whereas bubble sort may require multiple passes.
想知道自己有幾分把握?
Thinka 是 DSE 學生用的 AI 練習應用程式,有無限量練習題、即時自動批改和詳細解題步驟。逾 100,000 名學生用它確認自己真的識,而不只是「以為識」。