IB DP · Thinka 原創模擬試題

2023 IB DP Computer Science 模擬試題連答案詳解

Thinka May 2023 HL (TZ2) IB Diploma Programme-Style Mock — Computer Science

195 270 分鐘2023
An original Thinka practice paper modelled on the structure and difficulty of the May 2023 HL (TZ2) IB Diploma Programme Computer Science paper. Not affiliated with or reproduced from IB.

卷一 甲部

Answer all questions. Short-answer core syllabus topics.
9 題目 · 25.020000000000003
題目 1 · Short Answer
2.78
Outline one compatibility issue that may arise when migrating data from a legacy database system to a modern database system.
查看答案詳解

解題

During migration, the legacy system may use outdated file structures, obsolete data types (such as two-digit year fields), or proprietary database schemas. If these do not map directly to the modern system's schema, the data must be transformed. This process can lead to data truncation, loss of historical data, or corruption if characters cannot be decoded correctly by the new system.

評分準則

Award [1 mark] for identifying a valid compatibility issue (e.g., schema difference, data type mismatch, outdated file format, or encoding issues). Award up to [1.78 marks] for explaining how this issue affects the migration process (e.g., requires complex data transformation, risks data loss/corruption, or causes system downtime).
題目 2 · Short Answer
2.78
Distinguish between the roles of the Program Counter (PC) and the Memory Address Register (MAR) during the fetch stage of the machine instruction cycle.
查看答案詳解

解題

At the beginning of the fetch stage, the address of the next instruction is stored in the PC. This address is then copied into the MAR. While the MAR uses this address to fetch the instruction from RAM via the address bus, the PC is incremented to point to the subsequent instruction in sequence.

評分準則

Award [1 mark] for clearly stating the function of the PC (storing the address of the next instruction). Award [1 mark] for clearly stating the function of the MAR (storing the active address for the memory bus). Award [0.78 marks] for distinguishing their relationship during the fetch stage (e.g., address is copied from PC to MAR, allowing the PC to increment independently).
題目 3 · Short Answer
2.78
Explain how packet switching enables data to be transmitted reliably even if a specific network node or link fails during transmission.
查看答案詳解

解題

In packet switching, the original message is divided into independent packets, each containing a header with the destination address. Routers dynamically calculate the optimal route for each packet. If a network node along the path fails, subsequent packets are automatically routed through alternative active paths. Once all packets reach the destination, they are reordered. If any packet is lost, the receiver requests a retransmission.

評分準則

Award [1 mark] for explaining that messages are divided into independent packets with routing headers. Award [1 mark] for describing dynamic routing (packets can take different paths to bypass broken nodes). Award [0.78 marks] for describing packet reassembly and error recovery/retransmission at the destination.
題目 4 · Short Answer
2.78
State the maximum number of comparisons required to find a target value in a sorted array of 200 elements using a binary search algorithm. Show your calculations.
查看答案詳解

解題

A binary search continually halves the search space. The maximum number of comparisons needed is calculated using \(\lfloor \log_2(N) \rfloor + 1\). For \(N = 200\): \(\log_2(200) \approx 7.64\). Therefore, \(\lfloor 7.64 \rfloor + 1 = 7 + 1 = 8\) comparisons. Alternatively, since \(2^7 = 128\) (insufficient) and \(2^8 = 256\) (sufficient to cover 200 elements), the maximum is 8 comparisons.

評分準則

Award [1 mark] for showing correct mathematical working (e.g., using log formula, halving sequence, or powers of 2). Award [1.78 marks] for the correct answer of 8 comparisons.
題目 5 · Short Answer
2.78
Compare a singly linked list with a doubly linked list by stating one advantage and one disadvantage of using a doubly linked list.
查看答案詳解

解題

A doubly linked list node contains references to both the next and the previous nodes, which allows traversal in both directions and simplifies deletion of nodes. However, this incurs a disadvantage: it requires more memory storage for the additional 'previous' pointers, and the insertion/deletion logic is more complex because more pointers must be updated.

評分準則

Award [1 mark] for a valid advantage (e.g., bidirectional traversal, more efficient deletion when pointing directly to a node). Award [1 mark] for a valid disadvantage (e.g., increased memory overhead for the extra pointer, more complex node manipulation). Award [0.78 marks] for a clear comparative contrast.
題目 6 · Short Answer
2.78
State how a closed-loop control system differs from an open-loop control system, and identify the key component that enables this difference.
查看答案詳解

解題

An open-loop control system performs an action based on a predetermined input or timer, without measuring the actual output or making corrections (e.g., a simple microwave timer). A closed-loop control system constantly monitors the output state using a sensor and feeds this data back to the controller to adjust the input and maintain a target state (e.g., a thermostat-controlled heater). The key component is the sensor that provides feedback.

評分準則

Award [1 mark] for explaining open-loop (predetermined, no feedback). Award [1 mark] for explaining closed-loop (self-correcting, uses output feedback). Award [0.78 marks] for identifying the sensor / feedback mechanism as the enabling component.
題目 7 · Short Answer
2.78
Explain how an operating system uses paging to execute a program that is larger than the available physical RAM.
查看答案詳解

解題

The operating system divides the program's logical address space into fixed-size blocks called pages, and divides the physical RAM into matching blocks called frames. When executing a large program, only the active pages are loaded into physical frames. If the CPU references a page not currently in RAM, a page fault is triggered, prompting the OS to swap an inactive frame back to secondary storage (virtual memory) and load the required page into its place.

評分準則

Award [1 mark] for explaining the concept of dividing memory into pages and frames. Award [1 mark] for explaining that only active pages reside in RAM while others remain on secondary storage. Award [0.78 marks] for describing the process of handling page faults and swapping pages dynamically.
題目 8 · Short Answer
2.78
Define the term 'polymorphism' in the context of object-oriented programming, and outline how it supports extensibility.
查看答案詳解

解題

Polymorphism is the OOP principle where objects of different classes can be treated as objects of a common superclass, and can override common methods to exhibit unique behaviors. It supports extensibility by decoupling client code from specific implementations; if a developer adds a new subclass later, it can be integrated seamlessly into the existing system without rewriting or recompiling the existing code that interacts with the superclass interface.

評分準則

Award [1 mark] for an accurate definition of polymorphism (different forms/behaviors for the same method call). Award [1 mark] for explaining how it relates to overriding or interfaces. Award [0.78 marks] for outlining how it provides extensibility (adding new classes without breaking or changing existing core code).
題目 9 · Short Answer
2.78
Outline the role of the Memory Address Register (MAR) and the Memory Data Register (MDR) during the fetch stage of the machine instruction cycle.
查看答案詳解

解題

1. The Program Counter (PC) holds the address of the next instruction, which is copied to the Memory Address Register (MAR). 2. The MAR sends this address along the address bus to RAM. 3. RAM retrieves the instruction at that address and sends it along the data bus to the Memory Data Register (MDR), where it is temporarily stored before decoding.

評分準則

Award marks as follows (up to a maximum of 2.78 / 3 marks): - 1 mark: for stating that the MAR holds/receives the memory address of the next instruction (from the Program Counter). - 1 mark: for stating that the MAR sends this address to RAM/primary memory via the address bus. - 1 mark: for stating that the MDR receives and temporarily stores the instruction/data retrieved from RAM via the data bus.

卷一 乙部

Answer all questions. Scenario-based structured programming and systems problems.
5 題目 · 75
題目 1 · Long Answer
15
A large retail company is planning to migrate its legacy point-of-sale (POS) database and system to a new cloud-based ERP (Enterprise Resource Planning) platform.

(a) Explain two disadvantages of using a direct changeover method for this migration. [4]
(b) Describe how user acceptance testing (UAT) can be conducted to ensure the reliability of the new ERP system. [4]
(c) Discuss two issues related to data migration that the technical team must address before implementing the new system. [4]
(d) Identify three components of system documentation that must be provided to end-users (retail staff) during training. [3]
查看答案詳解

解題

(a) Disadvantages of direct changeover: (1) High risk: If the new ERP system fails or has critical bugs, there is no fallback system available, which can immediately halt retail operations. (2) High pressure on staff: Staff must adapt to the new system immediately without any transition period, increasing the likelihood of operational errors during busy hours.

(b) User Acceptance Testing (UAT): (1) UAT should involve representative end-users (e.g., store cashiers and inventory managers) performing real-world tasks (like processing transactions or updating stock) in a simulated test environment. (2) Feedback is collected, and bugs or usability issues are reported back to the development team to be fixed before final deployment, ensuring that the software meets operational requirements and is user-friendly.

(c) Data migration issues: (1) Data format incompatibility: The legacy system may use structured text or an outdated relational schema that does not match the new cloud ERP's database schema. This requires data mapping and transformation. (2) Data loss or corruption risk: Large-scale data transfers can suffer from transmission errors or incomplete transfers, necessitating checksum verification and comprehensive backups before starting the migration.

(d) System documentation components: (1) Step-by-step user manual/guide for daily tasks (e.g., checkout process). (2) FAQ / Troubleshooting guide for common errors. (3) Quick-reference cheat sheet for keyboard shortcuts and emergency procedures.

評分準則

Part (a): Award up to [4 marks] max.
- Award [1 mark] for identifying a disadvantage and [1 mark] for explaining it, up to 2 times.
- Disadvantages include: High risk of failure with no fallback, extreme pressure on staff, potential loss of business if downtime occurs.

Part (b): Award up to [4 marks] max.
- Award [1 mark] for mentioning the involvement of actual end-users.
- Award [1 mark] for testing under real-world scenarios or workflows.
- Award [1 mark] for mentioning the formal feedback/bug reporting cycle.
- Award [1 mark] for verifying that the system meets user requirements / sign-off.

Part (c): Award up to [4 marks] max.
- Award [1 mark] for identifying a migration issue and [1 mark] for discussing its impact or solution, up to 2 times.
- Issues include: Data format incompatibility/mapping, data validation/cleansing, risk of data loss/corruption, security during transfer.

Part (d): Award up to [3 marks] max.
- Award [1 mark] for each valid documentation component identified (e.g., user manual, quick-reference guide, troubleshooting guide, FAQs, training videos).
題目 2 · Long Answer
15
A logistics center uses a 2D array representing a warehouse grid of size 10 by 10. Each cell in the grid contains an integer representing the number of packages stored there. The grid is named WAREHOUSE.

(a) Construct a pseudocode algorithm that calculates and outputs the index of the row (0 to 9) with the maximum total packages. If multiple rows have the same maximum sum, output the index of the first such row. [8]
(b) Explain why a sequential search is more appropriate than a binary search for finding a specific package identifier in an unsorted 1D array of size N. [3]
(c) Outline how the efficiency of the pseudocode algorithm in part (a) would be affected if the grid size increased to 1000 by 1000, using Big O notation. [4]
查看答案詳解

解題

(a) Pseudocode:
maxRow = 0
maxSum = -1
loop R from 0 to 9
rowSum = 0
loop C from 0 to 9
rowSum = rowSum + WAREHOUSE[R][C]
end loop
if rowSum > maxSum then
maxSum = rowSum
maxRow = R
end if
end loop
output maxRow

(b) A binary search requires the data to be sorted to function correctly because it relies on dividing the search space in half based on comparison operations. Sorting an unsorted array of size N takes O(N log N) time, which is slower than a single sequential search taking O(N) time. Therefore, sequential search is more efficient and appropriate for a single search on unsorted data.

(c) The algorithm uses nested loops to traverse the grid. If the dimensions of the grid are N by N, the algorithm must visit every cell once, resulting in N * N operations. This gives a time complexity of O(N^2). If the grid size increases to 1000 by 1000, the number of executions of the inner loop body scales quadratically from 100 to 1,000,000 operations, making the time complexity highly dependent on grid dimensions.

評分準則

Part (a): Award up to [8 marks] max.
- Award [1 mark] for initializing tracking variables (maxRow, maxSum) correctly.
- Award [1 mark] for implementing the outer loop to traverse all 10 rows.
- Award [1 mark] for resetting the rowSum counter for each new row.
- Award [1 mark] for implementing the inner loop to traverse all 10 columns.
- Award [1 mark] for correctly accessing the 2D array elements using index variables.
- Award [1 mark] for correctly accumulating the row sum inside the inner loop.
- Award [1 mark] for implementing the conditional check (rowSum > maxSum) correctly.
- Award [1 mark] for updating maxRow and maxSum and outputting the result at the end.

Part (b): Award up to [3 marks] max.
- Award [1 mark] for stating that binary search requires the array to be sorted.
- Award [1 mark] for explaining that sorting takes additional time/overhead.
- Award [1 mark] for concluding that for a single search, O(N) sequential search is faster than sorting first.

Part (c): Award up to [4 marks] max.
- Award [1 mark] for identifying the current complexity as quadratic or O(N^2).
- Award [1 mark] for explaining that both dimensions (rows and columns) scale together.
- Award [1 mark] for calculating the scale of the change (from 10x10=100 operations to 1000x1000=1,000,000 operations).
- Award [1 mark] for stating that space complexity remains constant O(1) as only a few scalar variables are used.
題目 3 · Long Answer
15
A regional university is setting up a new campus-wide wireless network for its students and staff.

(a) Describe the roles of the DHCP server and the DNS server in allowing a student's laptop to connect to a website. [4]
(b) Explain how data packet switching ensures that a file is successfully transmitted from a web server to the laptop, even if some packets are lost or delayed during transmission. [5]
(c) Outline three security measures that the university can implement on the wireless network to protect sensitive academic data from unauthorized access. [6]
查看答案詳解

解題

(a) DHCP Server: Dynamically assigns an IP address, subnet mask, default gateway, and DNS server address to the student's laptop when it connects to the network. DNS Server: Translates user-friendly domain names (e.g., university.edu) into machine-readable IP addresses so that the laptop can establish a TCP connection.

(b) Packet Switching: (1) The file is split into smaller, manageable units called packets, each with a header containing source IP, destination IP, and sequence number. (2) Each packet is routed independently through the network based on the most efficient path available. (3) If a packet is lost or delayed, the receiving laptop identifies the missing sequence number and requests retransmission of that specific packet (using TCP protocols). (4) Once all packets arrive, they are reassembled in the correct order using their sequence numbers.

(c) Security Measures: (1) WPA3 Enterprise Encryption: Encrypts wireless traffic between laptops and access points using strong cryptographic keys, preventing eavesdropping. (2) 802.1X Authentication: Requires students and staff to log in using their unique university credentials via a RADIUS server, rather than a shared passphrase. (3) Network Segmentation (VLANs): Separates student traffic, staff traffic, and critical administrative servers onto different virtual networks to prevent unauthorized access across segments.

評分準則

Part (a): Award up to [4 marks] max.
- Award [2 marks] for DHCP: [1] for dynamic IP allocation, [1] for configuration parameters (gateway, subnet).
- Award [2 marks] for DNS: [1] for translation/resolution, [1] for mapping domain names to IP addresses.

Part (b): Award up to [5 marks] max.
- Award [1 mark] for stating files are divided into packets containing headers (IP addresses, sequence numbers).
- Award [1 mark] for stating packets travel independently along different paths.
- Award [1 mark] for describing how sequence numbers are used to reassemble the data in the correct order.
- Award [1 mark] for describing detection of missing/damaged packets at the destination.
- Award [1 mark] for explaining the mechanism of retransmission requests (e.g., TCP ACK/NACK).

Part (c): Award up to [6 marks] max.
- Award [1 mark] for identifying a security measure, and [1 mark] for outlining how it protects data, up to 3 times.
- Valid measures include: WPA3 encryption, 802.1X/RADIUS authentication, VLAN segmentation, MAC address filtering, Firewalls/IDS, VPNs for off-campus access.
題目 4 · Long Answer
15
A medical clinic uses a Priority Queue to manage patients waiting for treatment. Patients with a higher priority value (where 1 is low priority and 5 is emergency/high priority) must be seen before those with lower priority. If patients have the same priority, they are seen on a first-come, first-served basis. The queue is implemented using a dynamic linked list where each node has three fields: PatientName, Priority, and Next pointer.

(a) Draw or describe the structure of the linked list after the following sequential operations are executed (assuming the queue is initially empty):
1. Enqueue('Alice', 2)
2. Enqueue('Bob', 4)
3. Enqueue('Charlie', 2)
4. Dequeue()
Your description must clearly show the order of the nodes, their values, and pointer targets. [5]
(b) Construct a pseudocode algorithm for the enqueue(newName, newPriority) method that inserts a new patient into the correct position in the linked list based on their priority. [8]
(c) State one advantage and one disadvantage of using a linked list implementation of a priority queue over a static array-based implementation. [2]
查看答案詳解

解題

(a) Step-by-step state of the linked list:
- After Enqueue('Alice', 2): Head -> [ 'Alice', 2, Next -> null ]
- After Enqueue('Bob', 4): Head -> [ 'Bob', 4, Next ] -> [ 'Alice', 2, Next -> null ] (Bob has higher priority)
- After Enqueue('Charlie', 2): Head -> [ 'Bob', 4, Next ] -> [ 'Alice', 2, Next ] -> [ 'Charlie', 2, Next -> null ] (Charlie has same priority as Alice, so he is placed after Alice due to first-come first-served)
- After Dequeue(): Removes the head node ('Bob', 4).
Final List State: Head -> [ 'Alice', 2, Next ] -> [ 'Charlie', 2, Next -> null ]

(b) Pseudocode:
```
newNode = new Node(newName, newPriority)
if head == null then
head = newNode
else if newPriority > head.Priority then
newNode.Next = head
head = newNode
else
current = head
while current.Next != null and current.Next.Priority >= newPriority do
current = current.Next
end while
newNode.Next = current.Next
current.Next = newNode
end if
```

(c) Advantage: Dynamic memory allocation means the linked list does not have a fixed size limit, preventing overflow issues. Disadvantage: Extra memory is consumed to store the pointer addresses ('Next') for each node, and traversing the linked list to find the insertion point takes O(N) time compared to direct indexing.

評分準則

Part (a): Award up to [5 marks] max.
- Award [1 mark] for showing Alice correctly enqueued at first.
- Award [1 mark] for showing Bob correctly inserted at the head (before Alice).
- Award [1 mark] for showing Charlie correctly placed after Alice (same priority, stable ordering).
- Award [1 mark] for showing Dequeue correctly removes Bob.
- Award [1 mark] for showing correct pointer transitions, Head pointer, and null pointer at the tail.

Part (b): Award up to [8 marks] max.
- Award [1 mark] for creating the new node correctly with fields set.
- Award [1 mark] for checking the empty list boundary condition (head == null).
- Award [1 mark] for checking the 'insert at head' condition (newPriority > head.Priority).
- Award [1 mark] for updating head pointers correctly when inserting at the head.
- Award [1 mark] for initializing a traversal pointer (current = head).
- Award [1 mark] for implementing a loop to traverse nodes with higher or equal priority.
- Award [1 mark] for checking current.Next != null to prevent null pointer exceptions.
- Award [1 mark] for correctly adjusting Next pointers of current and newNode upon insertion.

Part (c): Award up to [2 marks] max.
- Award [1 mark] for a valid advantage (e.g., dynamic size, no resizing overhead).
- Award [1 mark] for a valid disadvantage (e.g., pointer memory overhead, lack of random access, sequential search required for insertion).
題目 5 · Long Answer
15
An automated hydroponic greenhouse uses a centralized control system to maintain optimal growing conditions for lettuce plants. The system regulates ambient temperature, water pH levels, and artificial light intensity.

(a) Explain the role of sensors and actuators in this automated control system, providing one specific example of each for the greenhouse. [4]
(b) Outline how the system uses a feedback loop to maintain the ambient temperature of the greenhouse within a target range of 20 degrees Celsius to 24 degrees Celsius. [5]
(c) Describe two social or ethical issues that could arise if the automated greenhouse control system fails due to a software glitch or power outage. [4]
(d) Identify two differences between an open-loop system and a closed-loop system in the context of control systems. [2]
查看答案詳解

解題

(a) Role of Sensors: Transducer devices that measure physical analog signals from the environment (e.g., temperature) and convert them into electrical signals for the microprocessor. Example: Thermistor/Temperature sensor. Role of Actuators: Devices that receive instructions from the microprocessor to perform physical work or change the state of the system. Example: Fan or heater.

(b) Feedback Loop Process: (1) Temperature sensors constantly measure the ambient greenhouse temperature. (2) This analog signal is converted to digital and sent to the controller. (3) The microprocessor compares the input temperature to the set range (20C - 24C). (4) If temperature < 20C, the microprocessor sends a signal to activate the heater actuator. If temperature > 24C, it activates the cooling fan actuator. (5) If it is within range, no action or shutdown of devices occurs. (6) The cycle repeats continuously, forming a closed feedback loop.

(c) Social/Ethical issues: (1) Economic ruin for the farmer: If the crop is ruined because of a temperature control failure, the farmer faces huge financial losses, affecting their livelihood and employees. (2) Environmental waste/Ethical duty: Ruining thousands of heads of lettuce contributes to massive food waste when regional food security might depend on sustainable agricultural output.

(d) Differences: (1) Feedback: Closed-loop systems use feedback from output sensors to adjust inputs; open-loop systems do not use feedback. (2) Autonomy: Closed-loop systems can self-correct dynamically; open-loop systems simply execute predefined actions regardless of actual outcome.

評分準則

Part (a): Award up to [4 marks] max.
- Award [1 mark] for defining a sensor and [1 mark] for a valid example (e.g., pH sensor, light sensor, temperature probe).
- Award [1 mark] for defining an actuator and [1 mark] for a valid example (e.g., water pump, grow lights, motor-controlled ventilation vents).

Part (b): Award up to [5 marks] max.
- Award [1 mark] for mentioning continuous measurement of temperature by sensors.
- Award [1 mark] for comparison against target thresholds (20C and 24C) by the processor.
- Award [1 mark] for identifying decision branch when temp is below 20C (activate heater).
- Award [1 mark] for identifying decision branch when temp is above 24C (activate fan/cooler).
- Award [1 mark] for explaining that the output actions change the environment, which is measured in the next cycle (feedback loop).

Part (c): Award up to [4 marks] max.
- Award [1 mark] for identifying an issue and [1 mark] for describing its societal/ethical impact, up to 2 times.
- Issues include: Loss of livelihood/income, food security/supply chain issues, environmental waste, safety of workers (if heaters/generators fail unsafely).

Part (d): Award up to [2 marks] max.
- Award [1 mark] for noting the presence/absence of a feedback mechanism.
- Award [1 mark] for noting the difference in self-correction or adaptability.

卷二 Option D

Answer all questions from the OOP option.
4 題目 · 65
題目 1 · Structured OOP
16.25
An online delivery system uses object-oriented programming to model items in its inventory. The class Item has the following attributes:
- id (String)
- price (double)
- quantity (int)

A subclass PerishableItem inherits from Item and has an additional attribute:
- expiryDays (int)

(a) Describe the inheritance relationship between Item and PerishableItem, identifying which class is the superclass and which is the subclass, and state the UML notation used to represent this relationship. [3 marks]

(b) Write the Java code for the Item class constructor and a method public double calculateTotalValue() which returns the total monetary value of this item currently in stock (price multiplied by quantity). [4 marks]

(c) Write the Java code for the PerishableItem class constructor, ensuring it correctly initializes all attributes (using super), and override the calculateTotalValue() method. If expiryDays is less than 3, a 50% discount must be applied to the calculated total value; otherwise, the standard value is returned. [5 marks]

(d) Explain the concept of polymorphism and describe how the JVM determines which implementation of calculateTotalValue() to execute when iterating through an array of type Item[] that contains both standard and perishable items. [4.25 marks]
查看答案詳解

解題

Part (a):
- Item is the superclass (parent class) and PerishableItem is the subclass (child class).
- This represents an "is-a" relationship where PerishableItem is a specialized type of Item.
- In UML diagrams, inheritance is represented by a solid line with a hollow arrowhead pointing from the subclass (PerishableItem) to the superclass (Item).

Part (b):
```java
public class Item {
private String id;
private double price;
private int quantity;

public Item(String id, double price, int quantity) {
this.id = id;
this.price = price;
this.quantity = quantity;
}

public double calculateTotalValue() {
return this.price * this.quantity;
}
}
```

Part (c):
```java
public class PerishableItem extends Item {
private int expiryDays;

public PerishableItem(String id, double price, int quantity, int expiryDays) {
super(id, price, quantity);
this.expiryDays = expiryDays;
}

@Override
public double calculateTotalValue() {
double standardValue = super.calculateTotalValue();
if (this.expiryDays < 3) {
return standardValue * 0.5;
}
return standardValue;
}
}
```

Part (d):
- Polymorphism is the ability of an object to take on many forms. Subtype polymorphism allows a subclass method to override a superclass method with the same signature.
- When iterating through an Item[] array, the reference type is Item. However, at runtime, the Java Virtual Machine (JVM) uses dynamic binding (late binding) to determine the actual object type.
- If the object in the array is a PerishableItem, the JVM invokes the overridden calculateTotalValue() method of PerishableItem. If it is a standard Item, it executes the superclass method.

評分準則

Part (a) [3 Marks]
- [1 mark] Correctly identifying Item as the superclass and PerishableItem as the subclass.
- [1 mark] Identifying the relation as an "is-a" relationship.
- [1 mark] Stating that the UML notation is a solid line with a hollow arrowhead pointing from the subclass to the superclass.

Part (b) [4 Marks]
- [1 mark] Correct constructor signature and parameters for Item.
- [1 mark] Correct initialization of all fields using 'this'.
- [1 mark] Correct method signature for calculateTotalValue().
- [1 mark] Correct calculation and return of price * quantity.

Part (c) [5 Marks]
- [1 mark] Correct class header indicating inheritance (extends Item).
- [1 mark] Correct constructor signature including all 4 parameters.
- [1 mark] Correct use of super(id, price, quantity) as the first line of the constructor.
- [1 mark] Correct override of calculateTotalValue() calling super.calculateTotalValue() to get the base total.
- [1 mark] Correct conditional check on expiryDays and applying the 50% discount correctly.

Part (d) [4.25 Marks]
- [1 mark] Definition of polymorphism (the ability of a reference to take on different forms/behaviors).
- [1.25 marks] Explanation of dynamic binding / late binding at runtime.
- [1 mark] Clear distinction between compile-time reference type (Item) and runtime object type.
- [1 mark] Explanation that the JVM invokes the method corresponding to the actual instance type.
題目 2 · Structured OOP
16.25
A fitness tracking application is designed using OOP principles.

The Activity class represents a single fitness session and has private attributes:
- type (String, e.g., "Run", "Swim")
- duration (int, in minutes)
- caloriesBurned (double)

The User class manages a collection of these activities using a fixed-size array:
- private Activity[] workouts
- private int activityCount (tracks the actual number of activities currently stored in the array)

(a) Explain the concept of encapsulation as demonstrated by the use of private attributes in the Activity class, and state how other classes (such as User) can access these values. [3 marks]

(b) Implement the method public double totalCaloriesForType(String activityType) in the User class. This method must iterate through the stored activities, find those matching the specified activity type (ignoring case), and return the sum of their caloriesBurned. [5 marks]

(c) Implement the method public Activity getLongestWorkout() in the User class. This method must return the Activity object that has the greatest duration. If the list is empty (no activities stored), it should return null. [5 marks]

(d) Distinguish between aggregation and composition relationships. Identify which of these relationships is more appropriate for the connection between the User and Activity classes in this application, justifying your answer. [3.25 marks]
查看答案詳解

解題

Part (a):
- Encapsulation is the bundling of data and methods that operate on that data into a single unit, while restricting direct access to the object's components.
- Declaring attributes as private prevents external classes from modifying the internal state of an Activity object directly, maintaining data integrity.
- Access is provided through public getter methods (e.g., getType(), getCaloriesBurned(), getDuration()) and optionally setter methods if modification is allowed.

Part (b):
```java
public double totalCaloriesForType(String activityType) {
double totalCalories = 0.0;
for (int i = 0; i < this.activityCount; i++) {
if (this.workouts[i] != null && this.workouts[i].getType().equalsIgnoreCase(activityType)) {
totalCalories += this.workouts[i].getCaloriesBurned();
}
}
return totalCalories;
}
```

Part (c):
```java
public Activity getLongestWorkout() {
if (this.activityCount == 0) {
return null;
}

Activity longest = this.workouts[0];
for (int i = 1; i < this.activityCount; i++) {
if (this.workouts[i] != null && this.workouts[i].getDuration() > longest.getDuration()) {
longest = this.workouts[i];
}
}
return longest;
}
```

Part (d):
- Composition is a strong "has-a" relationship where the child object cannot exist independently of the parent object. If the parent is destroyed, all child objects are also destroyed.
- Aggregation is a weaker "has-a" relationship where child objects can exist independently of the parent object.
- In this scenario, composition is more appropriate because a workout Activity is unique to a specific User. If the User profile is deleted, those specific recorded physical workouts have no independent existence in the tracking app and should be destroyed along with the user.

評分準則

Part (a) [3 Marks]
- [1 mark] Define encapsulation as restricting direct access to object state / bundling data and methods.
- [1 mark] Explain that private prevents unauthorized or accidental modifications, ensuring data integrity.
- [1 mark] State that public getter/accessor methods are used to safely retrieve the values.

Part (b) [5 Marks]
- [1 mark] Correct method header and initial declaration of accumulator variable (initialized to 0.0).
- [1 mark] Correct loop structure iterating up to activityCount.
- [1 mark] Correct safe check for null before accessing array elements.
- [1 mark] Correct comparison using .equalsIgnoreCase() or .equals() on the activity type.
- [1 mark] Correct accumulation of calories using getCaloriesBurned() and returning the final total.

Part (c) [5 Marks]
- [1 mark] Correct check for empty collection (activityCount == 0) and returning null.
- [1 mark] Correctly initializing the longest activity to the first element.
- [1 mark] Correctly looping through the remaining elements of the array.
- [1 mark] Correctly comparing durations using getDuration() on the objects.
- [1 mark] Correctly updating the longest variable and returning it.

Part (d) [3.25 Marks]
- [1 mark] Distinguish between Composition (strong ownership, lifetime bound) and Aggregation (weak relationship, independent lifetime).
- [1.25 marks] Argue why Composition is suitable (a workout activity has no meaning without its specific User).
- [1 mark] Correct application of context (if user is deleted, activities are deleted).
題目 3 · Structured OOP
16.25
A smart home control system manages different electronic devices.

An abstract class Device has protected attributes:
- id (String)
- isOn (boolean)

It also contains the abstract method definition:
- public abstract void adjustSetting(int value);

The concrete subclass SmartLight extends Device and includes an additional attribute:
- brightness (int, ranges from 0 to 100 representing percentage)

(a) State two characteristics of an abstract class in Java. [2 marks]

(b) Write the complete class definition for SmartLight. Your code must include:
- the class header indicating inheritance,
- the constructor initializing id, isOn (initially false), and brightness (initially 0),
- the implementation of adjustSetting(int value), which sets brightness to the provided value if it is between 0 and 100 inclusive. If value is less than 0, set brightness to 0. If value is greater than 100, set brightness to 100. [6 marks]

(c) Outline the role and requirement of the super keyword within a subclass constructor. [3 marks]

(d) Discuss the benefits of declaring a collection as Device[] rather than SmartLight[] within the main controller class, with reference to the concept of extensibility. [5.25 marks]
查看答案詳解

解題

Part (a):
1. An abstract class cannot be instantiated directly using the new operator.
2. It can contain abstract methods (methods without a body) that must be implemented by any concrete subclass.

Part (b):
```java
public class SmartLight extends Device {
private int brightness;

public SmartLight(String id) {
super();
this.id = id;
this.isOn = false;
this.brightness = 0;
}

@Override
public void adjustSetting(int value) {
if (value < 0) {
this.brightness = 0;
} else if (value > 100) {
this.brightness = 100;
} else {
this.brightness = value;
}
}

public int getBrightness() {
return this.brightness;
}
}
```

Part (c):
- The super keyword is used to call the constructor of the parent class (superclass).
- It is a requirement that the superclass constructor must execute before the subclass constructor code runs, ensuring that the inherited state is properly initialized.
- If not explicitly written, Java automatically inserts a call to the default zero-argument superclass constructor super().

Part (d):
- Declaring the collection as Device[] allows for the storage of any object that inherits from Device (such as SmartLight, SmartThermostat, or SmartSpeaker).
- This provides immense extensibility: if a new smart device type (like SmartLock) is introduced in the future, it only needs to inherit from Device and implement adjustSetting().
- The central controller class does not need to be modified or rewritten to handle the new device type, because it operates on the polymorphic Device reference and calls adjustSetting(), which executes the correct subclass implementation at runtime. This reduces coupling and supports software maintenance.

評分準則

Part (a) [2 Marks]
Award [1 mark] for each characteristic up to [2 marks]:
- Cannot be instantiated.
- Can contain abstract methods (methods without bodies).
- Can contain both abstract and concrete methods.
- Designed to be a superclass.

Part (b) [6 Marks]
- [1 mark] Correct class header public class SmartLight extends Device.
- [1 mark] Correct declaration of brightness private attribute.
- [1 mark] Correct constructor signature and explicit or implicit call to super().
- [1 mark] Correctly initializing id, isOn to false, and brightness to 0.
- [1 mark] Correct implementation of adjustSetting(int value) checking bounds (clamping lower limit to 0 and upper limit to 100).
- [1 mark] Correct assignment of the parameter value to brightness if within limits.

Part (c) [3 Marks]
- [1 mark] Explanation that super calls the superclass constructor.
- [1 mark] Explaining that it must be the first statement in the subclass constructor.
- [1 mark] Stating that it ensures proper initialization of the inherited attributes from the superclass before subclass logic is executed.

Part (d) [5.25 Marks]
- [1 mark] Identify that Device[] allows for heterogeneous storage (holding multiple different subclasses).
- [1.25 marks] Explain that the controller can use polymorphic method calls (adjustSetting()) without knowing the specific subtype.
- [1.5 marks] Define extensibility in this context: adding new devices (like SmartThermostat) without changing the existing controller code.
- [1.5 marks] Discuss reduction in code duplication and lower coupling between the controller and individual device classes.
題目 4 · Structured OOP
16.25
A flight reservation system models the passenger cabin using a 2D array of objects.

The class Seat has the following attributes:
- row (int, 1 to 30)
- letter (char, 'A' to 'F')
- isReserved (boolean)
- passengerName (String)

It has a constructor public Seat(int row, char letter) which initializes the row and letter, sets isReserved to false, and passengerName to null. It also has standard accessor and mutator methods.

The class Flight represents the aircraft cabin containing a 2D array of Seat objects:
- private Seat[][] cabin of dimensions 30 rows by 6 columns (representing columns A to F)

(a) Write the constructor for the Flight class. The constructor must initialize the cabin array and instantiate every Seat object in the 2D array. Map column indices 0 to 5 to characters 'A' through 'F'. [5 marks]

(b) Write the method public boolean reserveSeat(int row, char letter, String name) in the Flight class. This method must:
- Validate that the row (1 to 30) and letter ('A' to 'F') are within valid bounds. Return false if invalid.
- Determine if the targeted seat is already reserved. If so, return false.
- If available, reserve the seat by setting passengerName to name, changing isReserved to true, and returning true. [5 marks]

(c) Write the method public double getOccupancyRate() in the Flight class. This method must calculate and return the percentage of seats currently reserved on the flight (as a double value between 0.0 and 100.0). [3.25 marks]

(d) Discuss one advantage and one disadvantage of using a static 2D array of objects (like Seat[][]) rather than a dynamic structure (like ArrayList) to represent the seating layout in this system. [3 marks]
查看答案詳解

解題

Part (a):
```java
public class Flight {
private Seat[][] cabin;

public Flight() {
this.cabin = new Seat[30][6];
char[] letters = {'A', 'B', 'C', 'D', 'E', 'F'};

for (int r = 0; r < 30; r++) {
for (int c = 0; c < 6; c++) {
this.cabin[r][c] = new Seat(r + 1, letters[c]);
}
}
}
}
```

Part (b):
```java
public boolean reserveSeat(int row, char letter, String name) {
if (row < 1 || row > 30) {
return false;
}
int colIndex = letter - 'A';
if (colIndex < 0 || colIndex > 5) {
return false;
}

Seat targetSeat = this.cabin[row - 1][colIndex];
if (targetSeat.isReserved()) {
return false;
}

targetSeat.setPassengerName(name);
targetSeat.setReserved(true);
return true;
}
```

Part (c):
```java
public double getOccupancyRate() {
int totalSeats = 30 * 6;
int reservedCount = 0;

for (int r = 0; r < 30; r++) {
for (int c = 0; c < 6; c++) {
if (this.cabin[r][c] != null && this.cabin[r][c].isReserved()) {
reservedCount++;
}
}
}

return ((double) reservedCount / totalSeats) * 100.0;
}
```

Part (d):
- Advantage: Direct and fast access: A 2D array provides O(1) constant-time access to any seat via mathematical row and column indices (e.g., cabin[row - 1][col]), whereas searching an ArrayList might require O(N) sequential search. It also physically models the real-world structure of cabin seating (rows and columns).
- Disadvantage: Inflexible size: The dimensions of a static array are fixed upon creation. If the airline changes the flight to a larger aircraft (e.g., with 40 rows or 8 columns), the array size cannot be dynamically adjusted without instantiating a completely new array and copying the data over.

評分準則

Part (a) [5 Marks]
- [1 mark] Correctly instantiating the 2D array: this.cabin = new Seat[30][6];
- [1 mark] Nested loop structures spanning exactly 30 rows and 6 columns.
- [1 mark] Map loop index to seat row number correctly (r + 1).
- [1 mark] Map loop index to character 'A' through 'F' correctly (using array or ASCII arithmetic).
- [1 mark] Instantiate each element with new Seat(...).

Part (b) [5 Marks]
- [1 mark] Validate the row bounds (1 to 30).
- [1 mark] Correctly translate character letter to column index (e.g., letter - 'A') and validate bounds.
- [1 mark] Correctly retrieve the targeted Seat object and check if it is reserved (using accessor, e.g., isReserved()).
- [1 mark] Correctly set the passengerName and set isReserved to true.
- [1 mark] Correctly return true on successful booking and false for invalid inputs/reserved seats.

Part (c) [3.25 Marks]
- [1 mark] Correctly iterate through all 180 elements of the 2D array.
- [1 mark] Accumulate count of reserved seats based on checking isReserved() on the object.
- [1.25 marks] Correctly calculate and return the percentage as a floating-point value (using cast (double) to avoid integer division truncation).

Part (d) [3 Marks]
- [1.5 marks] For explaining a valid advantage (e.g., direct indexed access O(1), physical-to-logical conceptual mapping).
- [1.5 marks] For explaining a valid disadvantage (e.g., fixed memory size, cannot handle varying aircraft cabin sizes dynamically, wastes memory if sizes change).

Paper 3 Case Study

Answer all questions based on the Case Study.
4 題目 · 30
題目 1 · Case Study Analysis
7.5
EcoFly Logistics uses autonomous delivery drones in a dense urban environment. When managing collision avoidance, the system architects must choose between localized Peer-to-Peer (P2P) communication (using Wi-Fi Direct) and centralized communication (via a 5G cellular network). Explain how the choice of communication protocol impacts the latency, reliability, and local safety of the drone fleet during real-time obstacle avoidance.
查看答案詳解

解題

1. Latency: P2P (Wi-Fi Direct) allows direct drone-to-drone transmission, bypassing the routing overhead of cellular towers and central servers. This achieves sub-millisecond response times critical for immediate evasion maneuvers. 5G, while fast, involves transmission to a base station, core network routing, and central coordination, introducing higher round-trip latency (typically 5 to 20ms) which may be too slow for high-speed dynamic avoidance. 2. Reliability: P2P operates independently of external infrastructure, meaning it remains functional even during widespread power or telecom outages. However, its signal can be severely attenuated by concrete structures and electromagnetic interference in cities. 5G provides robust protocols and licensed spectrums with less interference, but creates a single point of failure (the cellular tower or central controller). 3. Safety Trade-offs: For local safety (avoiding a drone right ahead), P2P is superior due to guaranteed direct visibility. For strategic safety (avoiding areas with high traffic congestion or adverse localized micro-climates), 5G is superior as it offers a centralized macro-view of the entire airspace.

評分準則

Award up to 7.5 marks in total: Up to 2 marks for analyzing the impact of latency on real-time collision avoidance for both P2P and 5G. Up to 2 marks for explaining reliability differences (infrastructure independence of P2P vs. structured robustness of 5G). Up to 2.5 marks for discussing the local safety implications (micro-level reactions vs. macro-level path coordination). Up to 1 mark for technical accuracy and structured, logical comparison of the two paradigms.
題目 2 · Case Study Analysis
7.5
To safely navigate urban obstacles, EcoFly drones are equipped with high-resolution optical cameras that continuously capture video logs of their surroundings. Discuss the ethical and security implications of storing these video logs, and evaluate the effectiveness of utilizing onboard edge-processing as a mitigation strategy to protect citizen privacy.
查看答案詳解

解題

1. Ethical Implications: Continuous surveillance in public and private spaces (e.g., drones flying near residential windows) violates spatial privacy. Citizens cannot give active consent to being filmed by delivery drones, raising ethical dilemmas regarding the commodification of public spaces. 2. Security Implications: Storing raw high-resolution video logs creates a massive data liability. If a drone is physically captured or its storage systems are breached remotely, unauthorized parties could access historical recordings of citizens, security setups of buildings, and daily routines of individuals. 3. Mitigation Evaluation (Edge-Processing): Edge-processing solves the core security issue by transforming raw video into anonymous mathematical vectors (e.g., depth maps, object bounding boxes) directly on the drone's hardware. The raw video is discarded from volatile memory (RAM) instantly, meaning no personal data is written to non-volatile storage or transmitted over the network. 4. Limitations of Mitigation: While highly effective for privacy, edge-processing increases the weight, cost, and power consumption of the drone due to the need for powerful processor chips. This reduces flight times and payload capacity, representing a classic trade-off between privacy compliance and operational efficiency.

評分準則

Award up to 7.5 marks in total: Up to 2 marks for explaining the ethical implications of continuous urban drone surveillance. Up to 2 marks for identifying and explaining the security risks associated with storing raw high-resolution video footage. Up to 2.5 marks for evaluating the effectiveness of onboard edge-processing as a mitigation strategy, including its privacy benefits. Up to 1 mark for recognizing the technical/physical trade-offs of edge-processing (computational overhead, power usage, drone weight).
題目 3 · Case Study Analysis
7.5
EcoFly's onboard microprocessors must dynamically recalculate flight paths when unexpected obstacles (such as construction cranes) appear. Compare how the standard Dijkstra algorithm and the A* algorithm differ in balancing computational overhead and pathfinding efficiency when executed on power-constrained drone hardware.
查看答案詳解

解題

1. Dijkstra's Search Space: Dijkstra expands radially from the drone's current position, evaluating every potential node in the urban grid. In a 3D dynamic environment, this leads to an exponential explosion of nodes to process, causing high memory utilization and CPU stress, which drains the drone's battery and delays real-time maneuvering. 2. A* and Heuristics: A* optimizes the search by adding a heuristic function, \(f(n) = g(n) + h(n)\), where \(h(n)\) estimates the cost from node \(n\) to the final delivery point. This restricts the search to a narrow beam oriented toward the destination, resulting in faster execution times and minimal memory footprint. 3. Constraint Analysis: On power-constrained drone hardware, CPU execution time translates directly to power consumption. A* is highly preferred because it minimizes active computation cycles. However, if the dynamic obstacle environment changes constantly, calculating a complex heuristic for many moving objects can introduce its own processing overhead. Additionally, if the heuristic is not admissible (i.e., it overestimates the actual distance), A* may yield a sub-optimal, longer flight path, which also wastes battery in the long run.

評分準則

Award up to 7.5 marks in total: Up to 2 marks for describing how Dijkstra's algorithm operates (radial, unguided expansion) and its resulting computational impact on resource-constrained systems. Up to 2 marks for explaining how the A* algorithm utilizes a heuristic function \(f(n) = g(n) + h(n)\) to guide the search space. Up to 2.5 marks for analyzing the direct trade-offs on drone hardware (power consumption, processing speed, memory limits, and the risk of sub-optimality due to non-admissible heuristics). Up to 1 mark for precise technical comparison and use of algorithmic terms (search space, heuristic, admissibility, computational complexity).
題目 4 · Case Study Analysis
7.5
EcoFly is designing a protocol for package handoffs between aerial drones and automated ground vehicles (AGVs). They are debating between using a centralized relational database and a distributed ledger technology (DLT) like blockchain to record these handoffs. Evaluate this decision with respect to system latency, data immutability, and operational trust.
查看答案詳解

解題

1. System Latency: Centralized databases execute ACID-compliant transactions in milliseconds, allowing rapid status updates during the critical seconds a drone aligns with an AGV. DLTs require distributed consensus, which takes seconds or minutes to confirm blocks. This delay can stall physical handoff actions or lead to desynchronization between the physical position of the cargo and its digital record. 2. Data Immutability and Security: Once written to a blockchain, the handoff record is cryptographically secured and nearly impossible to alter or delete. This prevents bad actors (or software bugs) from retroactively altering the transaction log to hide package damage or theft. A centralized database lacks this native immutability; anyone with DBA (Database Administrator) privileges can modify logs, making it less secure against insider threats or targeted hacks. 3. Operational Trust: In scenarios where EcoFly collaborates with third-party logistics networks, a shared, permissioned DLT acts as a single, trusted source of truth without requiring any party to trust another's internal IT systems. With a centralized database, the hosting party holds all power, forcing other participants to trust their records blindly. Thus, DLT provides superior multi-organizational trust at the cost of operational speed.

評分準則

Award up to 7.5 marks in total: Up to 2 marks for evaluating the impact of system latency on real-time physical handoffs (centralized DB speed vs. DLT consensus delays). Up to 2 marks for comparing data immutability and security risks (centralized vulnerability to DBA manipulation vs. DLT cryptographic sequencing). Up to 2.5 marks for discussing operational trust in multi-party logistics scenarios (trustless shared state vs. single-owner control). Up to 1 mark for providing a balanced, clear conclusion or recommendation based on the physical requirements of the handoff system.

想知道自己有幾分把握?

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

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

免費開始練習