An original Thinka practice paper modelled on the structure and difficulty of the May 2024 HL (TZ2) IB Diploma Programme Computer Science paper. Not affiliated with or reproduced from IB.
Paper 1 Section A
Answer all questions. Short-answer core syllabus topics.
11 PastPaper.question · 24.97 PastPaper.marks
PastPaper.question 1 · Recall
2.27 PastPaper.marks
Explain one major disadvantage of using the direct changeover method instead of the parallel running method when implementing a new computer system.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Direct changeover involves completely decommissioning the old system and immediately starting the new one. If the new system encounters a critical failure, there is no backup system currently running to fall back on (unlike in parallel running, where the old system remains fully operational). This can lead to massive disruption of business activities and data loss.
PastPaper.markingScheme
Award up to 2.27 marks: [1 mark] for identifying the lack of a backup or fallback system in the event of a critical failure; [1 mark] for explaining the direct impact of this failure, such as operational downtime, data loss, or business disruption.
PastPaper.question 2 · Recall
2.27 PastPaper.marks
Describe the role of the Program Counter (PC) register during the fetch phase of the machine instruction cycle.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
At the start of the machine cycle, the Program Counter (PC) holds the address of the next instruction. This address is sent to the Memory Address Register (MAR) via the address bus. Simultaneously or immediately after, the PC is incremented by one (or by the instruction length) so that it points to the next sequential instruction, preparing for the subsequent cycle.
PastPaper.markingScheme
Award up to 2.27 marks: [1 mark] for stating that the PC holds the address of the next instruction to be fetched; [1 mark] for explaining that its value is copied to the MAR and then incremented to point to the next instruction.
PastPaper.question 3 · Recall
2.27 PastPaper.marks
Outline the primary function of a gateway in a local area network (LAN) connected to the Internet.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A gateway serves as the entry and exit point for a network. Its primary function is to translate and convert protocols between different network architectures. For instance, it translates local private network traffic (LAN) into protocols suitable for public networks (WAN/Internet) and vice versa, enabling heterogeneous networks to communicate.
PastPaper.markingScheme
Award up to 2.27 marks: [1 mark] for identifying that it connects two different networks (LAN and external WAN/Internet) that use different protocols; [1 mark] for describing its translation/conversion role that allows communication to flow between these distinct environments.
PastPaper.question 4 · Simple Application
2.27 PastPaper.marks
An array contains the following sorted integers: `[3, 8, 12, 17, 24, 31, 45]`. Describe the execution steps of a binary search algorithm looking for the target value 31, specifying the 'mid' index and values examined at each step. Use 0-based indexing.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
In the first step, the search range is index 0 to 6. The middle index is calculated as \(\lfloor(0 + 6) / 2\rfloor = 3\). The element at index 3 is 17. Since the target 31 is greater than 17, the left half is discarded, and the new search range becomes index 4 to 6. In the second step, the middle index is calculated as \(\lfloor(4 + 6) / 2\rfloor = 5\). The element at index 5 is 31, which matches our target. The algorithm successfully terminates.
PastPaper.markingScheme
Award up to 2.27 marks: [1 mark] for identifying the first mid-point at index 3 (value 17) and narrowing the search space to the upper half (indices 4-6); [1 mark] for identifying the second mid-point at index 5 (value 31) and successfully matching the target.
PastPaper.question 5 · Recall
2.27 PastPaper.marks
Compare a dynamic queue implemented with a linked list to a static queue implemented with an array, focusing on memory allocation and size flexibility.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A static queue's maximum capacity is predefined and fixed during memory allocation (usually stored in contiguous array blocks), which can lead to queue overflow if the limit is exceeded or wasted memory if the queue is mostly empty. In contrast, a dynamic queue (using a linked list) allocates memory on the heap only when new elements are added. It has no arbitrary upper limit (other than total system memory) and does not waste unused contiguous blocks, but it does carry a slight overhead because each node must store pointer references to the next node.
PastPaper.markingScheme
Award up to 2.27 marks: [1 mark] for comparing the memory allocation (static array-based queue uses fixed contiguous memory allocated upfront, while dynamic linked list-based queue allocates memory dynamically at runtime for each element); [1 mark] for comparing the size flexibility (static queue has fixed size limits leading to potential overflow/wastage, whereas dynamic queue grows/shrinks flexibly with pointer overhead).
PastPaper.question 6 · Recall
2.27 PastPaper.marks
Identify two physical hardware resources that an operating system must manage, and for each, outline one consequence of inefficient management.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
The operating system is a resource allocator. Two physical resources are: 1. RAM (Primary Memory): If managed inefficiently, the system may run out of address space, forcing heavy reliance on virtual memory (secondary storage) and leading to thrashing, which severely degrades system performance. 2. CPU (Central Processing Unit): Inefficient scheduling algorithms can lead to process starvation (where low-priority processes never get execution time) or poor multitasking throughput, causing system unresponsiveness.
PastPaper.markingScheme
Award up to 2.27 marks: [1 mark] for identifying two valid physical hardware resources (e.g., RAM, CPU, disk storage, network interface); [1 mark] for outlining a clear, negative consequence of inefficient management for both identified resources (e.g., thrashing for RAM, process starvation for CPU).
PastPaper.question 7 · Recall
2.27 PastPaper.marks
Explain the necessity of an Analog-to-Digital Converter (ADC) in an automated greenhouse control system that monitors soil moisture.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Environmental sensors, such as soil moisture probes, capture physical changes and translate them into continuous analog electrical voltages. Microprocessors and computer control units operate purely on discrete digital data (binary 0s and 1s). The Analog-to-Digital Converter (ADC) is necessary because it samples the analog signal and converts it into a digital representation, allowing the processor to interpret the moisture level and execute control commands (such as opening a water valve).
PastPaper.markingScheme
Award up to 2.27 marks: [1 mark] for identifying that the sensor outputs continuous analog signals while the controller/computer requires discrete digital signals; [1 mark] for explaining that the ADC translates between these two formats so the system can process and act upon the sensor data.
PastPaper.question 8 · Recall
2.27 PastPaper.marks
In the context of Object-Oriented Programming (OOP), explain the difference between method overloading and method overriding.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
Method overloading is a compile-time (static) polymorphism feature where a single class defines multiple methods with the exact same name but different signatures (different number, types, or order of parameters). Method overriding is a run-time (dynamic) polymorphism feature where a subclass provides its own specific implementation of a method that is already defined in its parent class, keeping the exact same name, return type, and parameters.
PastPaper.markingScheme
Award up to 2.27 marks: [1 mark] for a correct explanation of method overloading (same class, same method name, different signatures); [1 mark] for a correct explanation of method overriding (different classes in an inheritance hierarchy, same method name, same signatures).
PastPaper.question 9 · Short-answer
2.27 PastPaper.marks
Identify two benefits of creating a prototype during the design phase of a new computer system.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A prototype is a simplified, working model of a system. By building a prototype: 1. Users can interact with a visual representation of the software, enabling them to give concrete feedback on usability and functionality. This reduces the risk of misunderstanding requirements. 2. Developers can test specific technical concepts and find design flaws or omissions early in the system development life cycle, which is significantly cheaper to resolve than during or after the main implementation phase.
PastPaper.markingScheme
Award [1] mark for each valid benefit identified up to [2] marks (with the overall question scaled to 2.27 marks). Valid benefits include: - Allows for early user feedback/involvement. - Helps clarify and refine system requirements. - Identifies technical limitations or design flaws early. - Reduces overall development time and cost by preventing late-stage changes. - Assists in gaining stakeholder approval/funding.
PastPaper.question 10 · Short-answer
2.27 PastPaper.marks
Distinguish between Random Access Memory (RAM) and Read-Only Memory (ROM) in terms of volatility and writeability.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
RAM and ROM are two primary types of internal memory. RAM is volatile, meaning it requires electrical power to maintain its state and is used to store temporary data currently in use by the CPU. ROM is non-volatile, retaining its boot instructions (like the BIOS) even when the system is powered down. Furthermore, RAM allows high-speed read and write operations, while ROM is pre-written during manufacture and typically cannot be modified by standard user operations.
PastPaper.markingScheme
Award [1] mark for a correct distinction based on volatility (RAM is volatile vs ROM is non-volatile). Award [1] mark for a correct distinction based on writeability (RAM is read/write vs ROM is read-only). Max [2] marks total (scaled to 2.27 marks).
PastPaper.question 11 · Short-answer
2.27 PastPaper.marks
State two essential components contained within the header of a data packet transmitted over a packet-switched network.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
A packet consists of a header, payload, and sometimes a trailer. The header contains metadata necessary for routing and reassembling the packet. Essential components include the Source IP Address (to know where it came from and where to return errors), the Destination IP Address (so routers know where to forward the packet), the Packet Sequence Number (to reorder packets that arrive out of sequence), and a Checksum (to detect transmission errors).
PastPaper.markingScheme
Award [1] mark for each valid component identified up to [2] marks (scaled to 2.27 marks). Acceptable components: Destination IP address, Source IP address, Packet length/size, Protocol type, Packet sequence number, Checksum/error detection code, Time to Live (TTL).
Paper 1 Section B
Answer all questions. Scenario-based structured problems covering the core and HL extension.
5 PastPaper.question · 75 PastPaper.marks
PastPaper.question 1 · Algorithm Design
15 PastPaper.marks
A warehouse distribution system uses a singly linked list to manage outgoing packages. Each node in the linked list represents a Package object with properties: id (String), isExpress (Boolean), and next (pointer to the next node).
The system maintains two global pointers: head (pointing to the first node) and tail (pointing to the last node).
(a) Compare a linked list with a one-dimensional array in terms of memory utilization and insertion efficiency. [4 marks]
(b) Describe the steps required to insert a new package into the middle of a linked list (between two existing nodes). [3 marks]
(c) Construct a pseudocode algorithm for the method insertPriorityPackage(String newId, Boolean express) that inserts a new package. If the package is express (express == true), it must be placed at the front of the list (as the new head). If it is a standard package (express == false), it must be placed at the end of the list (updating the tail). Ensure all pointer updates (including empty list conditions) are handled correctly. [8 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Memory utilization: - Array: Static/fixed size allocated at compile time. Memory may be wasted if empty, but has no overhead for pointers. - Linked List: Dynamic size allocated at runtime. Memory is only used when elements are added, but there is memory overhead for storing the 'next' pointer/reference for each node.
Insertion efficiency: - Array: Insertion at the beginning/middle requires shifting elements, resulting in \(O(n)\) time complexity. - Linked List: Insertion requires only pointer updates, which is \(O(1)\) constant time once the insertion point is located.
(b) Steps to insert a new node (Node N) between two nodes (Node A and Node B): 1. Instantiate the new node N with the package data. 2. Traverse the list (or reference) to locate Node A. 3. Set Node N's 'next' pointer to point to Node A's current 'next' node (Node B). 4. Update Node A's 'next' pointer to point directly to Node N.
(c) Pseudocode Algorithm: ``` method insertPriorityPackage(newId, express) newNode = new Node(newId, express) if head == null then head = newNode tail = newNode else if express == true then newNode.next = head head = newNode else tail.next = newNode tail = newNode end if end if end method ```
PastPaper.markingScheme
(a) [4 marks] - 1 mark: Array has static size (wasted memory) vs Linked list has dynamic size. - 1 mark: Linked list has pointer overhead. - 1 mark: Array requires shifting elements during insertion (slow). - 1 mark: Linked list only requires updating reference pointers (fast, \(O(1)\)).
(b) [3 marks] - 1 mark: Instantiate the new node with data. - 1 mark: Point new node's 'next' to the successor node. - 1 mark: Point predecessor's 'next' to the new node.
(c) [8 marks] - 1 mark: Correct method signature and instantiation of Node object. - 2 marks: Correctly checking if the list is empty (`head == null`) and setting both `head` and `tail` to `newNode`. - 2 marks: Correct logic for express package (`express == true`), pointing `newNode.next` to `head` and updating `head` to `newNode`. - 2 marks: Correct logic for standard package (`express == false`), pointing current `tail.next` to `newNode` and updating `tail` to `newNode`. - 1 mark: Clear, logical structured pseudocode structure with correct end-if / end-method blocks.
PastPaper.question 2 · Extended Response
15 PastPaper.marks
A fitness tracking application is designed using object-oriented principles. The class Activity is the superclass, and Running is a subclass. The Activity class has private attributes: duration (minutes), avgHeartRate (bpm), and public getter methods. The Running class inherits from Activity and has an additional private attribute distance (kilometers).
(a) Outline the role of UML class diagrams in the planning and development of this software. [2 marks]
(b) Construct the class definition for the subclass Running in pseudocode, including its attributes, constructor (which initializes the inherited and new properties), and a getter method for distance. [5 marks]
(c) The application maintains an array of Activity objects named userWorkouts containing a mix of different activity types. Write a pseudocode algorithm for a method calculateTotalDistance(Activity[] userWorkouts) that iterates through the array, identifies which activities are instances of Running, calculates the total running distance covered, and returns this value. You may assume an operator instanceof is available. [8 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) UML class diagrams visually represent the static structure of the application, showing classes, attributes, methods, and relationships (such as the inheritance between Activity and Running). This helps developers map out object relationships before coding and guarantees standard implementation.
(b) Pseudocode Class Definition: ``` class Running extends Activity private double distance
constructor Running(int newDuration, int newAvgHeartRate, double newDistance) super(newDuration, newAvgHeartRate) this.distance = newDistance end constructor
public method getDistance() return this.distance end method end class ```
(c) Pseudocode Algorithm: ``` method calculateTotalDistance(userWorkouts) totalDistance = 0.0 loop i from 0 to userWorkouts.length - 1 if userWorkouts[i] != null then if userWorkouts[i] instanceof Running then runningActivity = (Running) userWorkouts[i] totalDistance = totalDistance + runningActivity.getDistance() end if end if end loop return totalDistance end method ```
PastPaper.markingScheme
(a) [2 marks] - 1 mark: Visual representation of class hierarchy/relationships (inheritance). - 1 mark: Facilitates communication among design/development teams or acts as a template for coding.
(b) [5 marks] - 1 mark: Correct class declaration with inheritance syntax (`extends Activity`). - 1 mark: Private attribute `distance` defined. - 2 marks: Constructor syntax initializing superclass variables via `super()` and assigning subclass distance. - 1 mark: Correct getter method for `distance` attribute.
(c) [8 marks] - 1 mark: Initializing accumulator variable `totalDistance` to 0.0. - 1 mark: Correct loop bounds iterating through the complete `userWorkouts` array. - 1 mark: Handling potential null elements in the array. - 2 marks: Correctly checking class type using `instanceof`. - 2 marks: Correctly casting the object to `Running` and accessing the subclass method `getDistance()`. - 1 mark: Returning the calculated total distance.
PastPaper.question 3 · Extended Response
15 PastPaper.marks
A remote weather station collects data and transmits it to a central forecasting office using a packet-switching network.
(a) Identify two advantages of using packet switching over circuit switching for this communication scenario. [2 marks]
(b) Explain the role of the following components in a packet: (i) Header [2 marks] (ii) Payload [2 marks]
(c) The network uses the TCP/IP model. Explain how TCP manages flow control and guarantees reliable packet delivery if a packet is lost during transmission. [5 marks]
(d) Describe how a collision occurs in a wireless network and outline a protocol used to prevent or resolve collisions. [4 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Advantages of packet switching: - More efficient utilization of network bandwidth because communication channels are shared dynamically rather than dedicated. - Resilient to network link failures as packets can take alternative routes to the destination.
(b) Roles: (i) Header: Contains crucial control and routing metadata such as source IP address, destination IP address, packet sequence number, and error-checking flags (checksum). (ii) Payload: The actual application data being transmitted, which in this case represents the environmental measurements (temperature, pressure, wind speed) from the weather station.
(c) TCP Reliability and Flow Control: - Sequencing: TCP numbers each packet so that the receiver can reassemble them in order. - Acknowledgements: The receiver sends back acknowledgment (ACK) packets when it successfully receives data. - Retransmission: If the sender does not receive an ACK within a designated timeout window, it assumes the packet was lost and retransmits it. - Flow Control: Uses a sliding window mechanism to regulate transmission rate based on the receiver's buffer capacity, preventing receiver overflow.
(d) Wireless Collisions: - A collision occurs when two or more wireless devices transmit data simultaneously on the same frequency band, causing signals to overlap, corrupt, and become unreadable. - CSMA/CA (Carrier Sense Multiple Access with Collision Avoidance) is used: devices listen to the channel before transmitting. If busy, they wait a random backoff time. They may also use RTS/CTS (Request to Send / Clear to Send) handshake frames to reserve the channel.
(b) [4 marks] - 2 marks: Header definition indicating routing data (source/destination IP) and meta-information. - 2 marks: Payload definition as actual payload data/weather measurements being transferred.
(c) [5 marks] - 1 mark: Sequencing packets sequentially to allow reassembly. - 1 mark: Sending back ACKs upon successful receipt. - 1 mark: Retransmission of unacknowledged packets after timeouts. - 1 mark: Sliding window mechanism to control pacing of packet transmission. - 1 mark: Buffer limit awareness (preventing overflow).
(d) [4 marks] - 1 mark: Definition of collision (simultaneous signal transmission on a single channel resulting in corruption). - 1 mark: Naming CSMA/CA protocol. - 1 mark: Outlining Carrier Sensing (listening to channel before transmission). - 1 mark: Outlining collision avoidance mechanisms like random backoff or RTS/CTS handshake.
PastPaper.question 4 · Algorithm Design
15 PastPaper.marks
An educational platform processes quiz scores for a class of students. The scores are stored in a two-dimensional array scores where each row represents a student and each column represents a quiz. There are numStudents students and numQuizzes quizzes.
(a) Explain why a two-dimensional array is an appropriate data structure for storing this information. [2 marks]
(b) Outline the steps of a selection sort algorithm to sort a one-dimensional array of integers in descending order. [4 marks]
(c) Write a pseudocode algorithm for a method findHighestAverages(int[][] scores, int numStudents, int numQuizzes) that: - Calculates the average score for each student. - Identifies and outputs the index of the student with the highest average. - Counts how many students scored above 80% on average, returning this count. [9 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) A 2D array naturally maps to a table or grid structure where one axis (rows) tracks a student's unique identifier/index and the other axis (columns) represents different quiz trials, keeping associated data contiguous and structured.
(b) Selection Sort (Descending Order): 1. Start at the first index of the array. 2. Search the remaining unsorted part of the array to find the maximum value. 3. Swap this maximum value with the value at the current index. 4. Move to the next index and repeat the search-and-swap process until the entire array is sorted.
loop s from 0 to numStudents - 1 sum = 0 loop q from 0 to numQuizzes - 1 sum = sum + scores[s][q] end loop avg = sum / numQuizzes
if avg > highestAvg then highestAvg = avg highestIndex = s end if
if avg > 80 then above80Count = above80Count + 1 end if end loop
output "Highest average student index: " + highestIndex return above80Count end method ```
PastPaper.markingScheme
(a) [2 marks] - 1 mark: Conceptual mapping (grid structure of students vs quizzes). - 1 mark: Constant-time access using row-column indices \(O(1)\).
(b) [4 marks] - 1 mark: Set outer tracking loop pointer. - 1 mark: Find the maximum value in the remainder of the array (descending order). - 1 mark: Swap maximum with value at current outer pointer position. - 1 mark: Correctly repeat/increment outer index until array bounds are reached.
(c) [9 marks] - 1 mark: Initialize highest tracking variables (`highestAvg`, `highestIndex`) and count accumulators. - 1 mark: Outer loop iterating over each student (row). - 1 mark: Reset student total sum variable on each iteration. - 1 mark: Inner loop iterating over all quizzes (columns) for current student. - 1 mark: Calculating correct running sum and division to get the `avg` value. - 1 mark: Comparison logic to track and update the maximum average and associated student index. - 1 mark: Comparison logic to count averages above 80. - 1 mark: Print/Output the calculated highest student index. - 1 mark: Correctly return the final counted value.
PastPaper.question 5 · Algorithm Design
15 PastPaper.marks
An embedded operating system in a smart home hub manages resource allocation for several concurrently running processes.
(a) Define the term 'multi-tasking' and explain how a single-core CPU simulates the concurrent execution of multiple processes. [3 marks]
(b) Describe how virtual memory can allow a system to run processes that require more memory than the physically installed RAM. [4 marks]
(c) The operating system uses a scheduling queue to manage three processes: A, B, and C. It uses a Round Robin scheduling algorithm with a time slice of 10 ms. The processes arrive at time 0 in the order A, B, C. Their execution times are: - Process A: 25 ms - Process B: 15 ms - Process C: 8 ms Construct a timeline or table showing the execution intervals of each process until completion, and calculate the average turnaround time for these three processes. [8 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Multi-tasking is the capability of an operating system to execute multiple processes apparently at the same time. On a single-core CPU, this is achieved by context switching, where the processor allocates brief periods of CPU time (time slices) to each process in rapid succession, creating the illusion of concurrent execution.
(b) Virtual Memory Mechanism: - Secondary storage (e.g., SSD/HDD) is used as an extension of physical RAM. - Active processes are divided into fixed-size blocks called pages, and physical memory is divided into frames. - Pages not actively needed are transferred to secondary storage (page swap out). When a process references a logical address belonging to a page on the secondary storage, a 'page fault' occurs, prompting the OS to load that page back into RAM (swap in).
(c) Round Robin Scheduling Analysis (Time slice = 10ms): Queue State Transitions: 1. [0ms - 10ms]: Process A runs (takes 10ms). Remaining time: A = 15ms. Queue: B, C, A. 2. [10ms - 20ms]: Process B runs (takes 10ms). Remaining time: B = 5ms. Queue: C, A, B. 3. [20ms - 28ms]: Process C runs (takes 8ms, completes). Queue: A, B. 4. [28ms - 38ms]: Process A runs (takes 10ms). Remaining time: A = 5ms. Queue: B, A. 5. [38ms - 43ms]: Process B runs (takes 5ms, completes). Queue: A. 6. [43ms - 48ms]: Process A runs (takes 5ms, completes).
Completion Times: - Process C: 28 ms - Process B: 43 ms - Process A: 48 ms
Turnaround Time (Completion Time - Arrival Time 0): - Turnaround A = 48 ms - Turnaround B = 43 ms - Turnaround C = 28 ms
Average Turnaround Time Calculation: \( \text{Average} = \frac{48 + 43 + 28}{3} = \frac{119}{3} \approx 39.67 \text{ ms} \)
PastPaper.markingScheme
(a) [3 marks] - 1 mark: Multi-tasking definition (running multiple processes concurrently). - 1 mark: Time slicing / Rapid scheduling allocation. - 1 mark: Concept of Context Switching (saving/loading states to simulate concurrency).
(b) [4 marks] - 1 mark: Use of secondary storage as a temporary extension of main RAM. - 1 mark: Dividing processes into fixed logical blocks called pages. - 1 mark: Concept of Page Fault (not finding a page in RAM). - 1 mark: Swapping pages between RAM and swap space to manage current operational demands.
(c) [8 marks] - 3 marks: Correctly tracking execution steps and process lengths (with context switching intervals matching quantum constraints). - 2 marks: Identifying exact process completion times: A at 48ms, B at 43ms, C at 28ms. - 2 marks: Correctly formulating Turnaround time for each process (Completion - Arrival). - 1 mark: Calculating the correct overall average: \( 119/3 \approx 39.67 \text{ ms} \) (accept rounded values).
Paper 2 Option D (OOP)
Answer all questions. Scenario-based object-oriented programming challenges in Java.
An international logistics company uses a software system to manage cargo ships. The CargoShip class stores an array of Container objects.
The Container class is defined as follows: ```java public class Container { private String id; private double weight; // in metric tons private double value; // in USD
public double getValue() { return this.value; } public double getWeight() { return this.weight; } } ```
The CargoShip class has the following attributes: ```java public class CargoShip { private String shipName; private Container[] cargoHold; private int containerCount; // actual number of containers currently loaded
public CargoShip(String shipName, int capacity) { this.shipName = shipName; this.cargoHold = new Container[capacity]; this.containerCount = 0; } } ```
(a) Write the Java method `calculateTotalValue()` for the `CargoShip` class. This method must calculate and return the total value of all loaded containers in the `cargoHold` array, taking into account that some slots in the array may be `null`. [6 marks]
(b) Describe one advantage of using an array of objects (`Container[]`) rather than multiple parallel arrays (e.g., `String[] containerIDs`, `double[] weights`, `double[] values`) to represent the cargo. [4.83 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Method implementation: ```java public double calculateTotalValue() { double total = 0.0; for (int i = 0; i < cargoHold.length; i++) { if (cargoHold[i] != null) { total += cargoHold[i].getValue(); } } return total; } ```
(b) Using an array of objects enforces encapsulation and data integrity. All attributes related to a single container are bound together within a single instance. If we used parallel arrays, deleting, sorting, or swapping a container would require manually modifying multiple arrays in synchrony, increasing the risk of mismatch errors.
PastPaper.markingScheme
(a) [6 marks total] - 1 mark: Initializing a running total double variable to 0. - 2 marks: Correct loop structure traversing the entire array (or up to containerCount safely). - 1 mark: Explicitly checking for null elements to prevent NullPointerException. - 1 mark: Accumulating correct value using `.getValue()`. - 1 mark: Returning the accumulated total with correct return type.
(b) [4.83 marks total] - 2 marks: Explaining how encapsulation groups data and actions together. - 1.83 marks: Discussing the risks of unsynchronized parallel arrays during sorting/deletion. - 1 mark: Mentioning ease of readability and code maintenance.
A smart home system manages different smart devices. A base class `SmartDevice` is defined as follows: ```java public class SmartDevice { private String deviceId; private boolean isOn;
public void turnOn() { this.isOn = true; } public void turnOff() { this.isOn = false; } public String getDeviceId() { return this.deviceId; } } ``` A subclass `Thermostat` inherits from `SmartDevice` and introduces an additional instance variable `temperature` (double) and a constructor.
(a) Construct the complete Java class definition for `Thermostat`, including its instance variable, its constructor (which must correctly call the superclass constructor), and a method `setTemperature(double temp)`. [6.83 marks]
(b) Explain how polymorphism allows a single array of type `SmartDevice[]` to store both `SmartDevice` and `Thermostat` objects, and how the program determines which method to execute at runtime. [4 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Code: ```java public class Thermostat extends SmartDevice { private double temperature;
(b) Polymorphism allows a subclass object to be treated as an instance of its superclass (substitution principle). Since `Thermostat` extends `SmartDevice`, any `Thermostat` object is-a `SmartDevice`. Therefore, a `SmartDevice[]` array can store references to both parent and child instances. At runtime, the Java Virtual Machine uses dynamic binding (late binding) to determine the actual object type and execute the appropriate overridden method.
PastPaper.markingScheme
(a) [6.83 marks total] - 1 mark: Class header `public class Thermostat extends SmartDevice`. - 1 mark: Correct private field declaration `private double temperature`. - 2 marks: Constructor accepting parameters and invoking `super(deviceId)` as first statement. - 1 mark: Correct initialization of subclass field `this.temperature`. - 1.83 marks: Correct definition of `setTemperature` mutator method.
(b) [4 marks total] - 2 marks: Explaining the "is-a" relationship allowing child objects in a parent-type array. - 2 marks: Explaining dynamic binding / late binding at runtime based on the actual object type.
public int getMemberId() { return this.memberId; } } ```
The `Library` class contains an array of members: ```java public class Library { private Member[] membersList; private int activeMemberCount; } ```
(a) Write the method `findMember(int targetId)` for the `Library` class, which performs a sequential search on the `membersList` array and returns the `Member` object if found, or `null` if the member is not in the list. Assume that `membersList` may contain `null` elements after the active elements or that the search should only check up to `activeMemberCount`. [5.83 marks]
(b) State the Big-O efficiency of this sequential search in the worst case, and explain why a binary search cannot be performed directly on this array if it is unsorted. [5 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Code: ```java public Member findMember(int targetId) { for (int i = 0; i < activeMemberCount; i++) { if (membersList[i] != null && membersList[i].getMemberId() == targetId) { return membersList[i]; } } return null; } ```
(b) The worst-case efficiency of a sequential search is \(O(N)\) where \(N\) is the number of elements. Binary search cannot be used on an unsorted array because the algorithm relies on the array being ordered. Without sorting, comparing a search value to the midpoint does not convey whether the target lies in the left or right half, rendering the divide-and-conquer strategy impossible.
PastPaper.markingScheme
(a) [5.83 marks total] - 1 mark: Correct method signature returning `Member`. - 2 marks: Iterating up to `activeMemberCount` or array length. - 1 mark: Safely handling potential null checks or boundary conditions. - 1 mark: Correctly comparing target ID with object's actual ID (`membersList[i].getMemberId() == targetId`). - 0.83 marks: Returning `null` if the loop completes without finding the member.
(b) [5 marks total] - 1 mark: Identifying efficiency as \(O(N)\). - 2 marks: Explaining that binary search uses a divide-and-conquer method based on ordered comparisons. - 2 marks: Demonstrating why midpoint comparisons are useless on an unsorted list.
public double getPrice() { return this.basePrice; } } ```
A subclass called `DiscountedProduct` is designed to apply a percentage discount to the base price of the product.
(a) Write the complete Java class for `DiscountedProduct`. The class should have an additional private instance variable `discountRate` (a double, e.g., 0.15 for 15% discount), a constructor that initializes all fields correctly, and an overridden `getPrice()` method that calculates and returns the discounted price using the superclass `getPrice()` method. [6.83 marks]
(b) Outline the concept of inheritance and how it supports code reuse in this scenario. [4 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Code: ```java public class DiscountedProduct extends Product { private double discountRate;
(b) Inheritance is an OOP mechanism where a new class (subclass) derives properties and behaviors from an existing class (superclass). In this scenario, `DiscountedProduct` inherits the `name` attribute and the initial logic, avoiding the duplication of those variables and constructor setups. Code is reused because we do not have to redefine name-tracking or standard price-tracking, only adding the specialized discount behavior.
PastPaper.markingScheme
(a) [6.83 marks total] - 1 mark: Correct class declaration with extends keyword. - 1 mark: Declaring private `discountRate` instance variable. - 2 marks: Constructor accepting three parameters and calling `super(name, basePrice)` appropriately. - 1 mark: Initializing `discountRate` instance variable. - 1.83 marks: Overriding `getPrice()` method utilizing `super.getPrice()` and applying discount calculation.
(b) [4 marks total] - 2 marks: Correct definition of inheritance (parent/child relationships). - 2 marks: Application to scenario explaining the avoidance of duplicate variables and logic.
An airport management simulation uses a queue to model aircraft waiting for a runway. The queue is implemented as a circular array of `Flight` objects within the `RunwayQueue` class.
The class definition is partially completed below: ```java public class RunwayQueue { private Flight[] queue; private int head; private int tail; private int size; private int maxCapacity;
(a) Write the `enqueue(Flight f)` method for the `RunwayQueue` class. The method should insert a `Flight` object at the tail of the queue, update the tail and size, and handle the circular nature of the queue. If the queue is already full, it should not add the flight and instead output an appropriate error message to the console. [6.83 marks]
(b) Identify two advantages of using a circular queue implementation over a standard linear array queue where elements are shifted left after each dequeue. [4 marks]
(b) Two advantages of circular queues: 1. Better time complexity: Dequeue is dynamic and takes \(O(1)\) time since we just update the head pointer, whereas shifting elements in a standard linear queue takes \(O(N)\) time. 2. Memory efficiency: It prevents wasting empty memory slots at the beginning of the array after objects are removed, as pointers wrap around to use free spaces.
PastPaper.markingScheme
(a) [6.83 marks total] - 1 mark: Checking if the queue is full (`size == maxCapacity`). - 1 mark: Printing appropriate error message on full queue condition. - 2 marks: Storing the `Flight` parameter `f` at index `tail`. - 1.83 marks: Safely incrementing the `tail` pointer using modulo operations to handle wrap-around. - 1 mark: Incrementing the `size` tracker.
(b) [4 marks total] - 2 marks: Discussing the time complexity advantages (eliminating shifting overhead, turning dequeue into \(O(1)\)). - 2 marks: Discussing space optimization and avoiding memory leakage/wastage.
A video game engine manages various in-game items. An interface `Item` is defined to specify standard behavior: ```java public interface Item { public String getName(); public int getWeight(); public void use(); } ```
(a) Implement a concrete class `Weapon` that implements the `Item` interface. The class should have instance variables for `name` (String), `weight` (int), and `damage` (int). Provide a constructor and all necessary methods to satisfy the interface, where the `use()` method prints to the console `"Swinging [name] for [damage] damage!"`. [6.83 marks]
(b) Discuss the design benefits of using an interface like `Item` instead of making `Item` a concrete superclass when creating dynamic collections of inventory items (e.g., weapons, armor, potions). [4 marks]
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
(a) Code: ```java public class Weapon implements Item { private String name; private int weight; private int damage;
public Weapon(String name, int weight, int damage) { this.name = name; this.weight = weight; this.damage = damage; }
@Override public String getName() { return this.name; }
@Override public int getWeight() { return this.weight; }
(b) Benefits of an interface: 1. Multiple implementation: A class can implement multiple interfaces (e.g., `Weapon` could implement `Item`, `Tradable`, and `Upgradable`), which is not possible with single inheritance from a concrete class. 2. Loose coupling: Interfaces define contract-based behaviors. Any external system managing inventories only needs to know that an object supports `Item` without concerning itself with subclass relationships, making it much easier to integrate entirely different item types (like magical elements) that do not fit in a rigid superclass hierarchy.
PastPaper.markingScheme
(a) [6.83 marks total] - 1 mark: Correct class declaration with `implements Item`. - 1 mark: Declaring three private fields: `name`, `weight`, and `damage`. - 2 marks: Constructor properly assigning arguments to fields. - 1.83 marks: Providing exact overridden methods `getName()` and `getWeight()`. - 1 mark: Implementing `use()` containing matching console printout.
(b) [4 marks total] - 2 marks: Discussing multiple interface support vs single inheritance limit. - 2 marks: Discussing decoupling, design flexibility, and dynamic expansion of completely unrelated classes under a shared interface.
Paper 3 Case Study
Answer all questions. Technical and societal evaluation based on the pre-issued Case Study.
Define the term 'Simultaneous Localization and Mapping (SLAM)' in the context of autonomous search-and-rescue robots. Evaluate the technical challenges of relying on LiDAR-based SLAM in smoke-filled, unstructured disaster environments, and suggest how alternative or complementary sensor modalities can mitigate these limitations.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
DEFINITION: Simultaneous Localization and Mapping (SLAM) is a computational process where an autonomous robot constructs a map of an unknown environment while tracking its own relative position within that map. TECHNICAL CHALLENGES OF LIDAR IN SMOKE: LiDAR operates by emitting infrared laser pulses and measuring their time of flight. In smoke, steam, or high-dust conditions, airborne particles refract and scatter these light pulses. This causes phantom obstacles (noise), drastically reduces sensor range, and causes localization failures due to incorrect point-cloud matching, leading to cumulative drift errors. ALTERNATIVE MODALITIES: To mitigate these issues, robots can integrate Thermal Cameras (FLIR) which detect longer wavelengths of infrared radiation emitted as heat, bypassing smoke particles. Additionally, Frequency-Modulated Continuous-Wave (FMCW) Radar uses longer millimeter waves that easily penetrate airborne particulates to provide reliable ranging. Finally, an Inertial Measurement Unit (IMU) can provide dead reckoning data to maintain localization during temporary optical sensor outages.
PastPaper.markingScheme
DEFINITION (2 Marks): Award 1 mark for mapping an unknown environment, and 1 mark for tracking the robot's coordinates within that environment. TECHNICAL EVALUATION (2.5 Marks): Award 1 mark for explaining physical scattering/refraction of light in smoke, 1 mark for detailing resulting errors (phantom obstacles, lost range), and 0.5 marks for explaining localization drift. MITIGATION MODALITIES (3 Marks): Award 1 mark for Thermal Cameras with heat penetration explanation, 1 mark for Radar with wavelength explanation, and 1 mark for IMU sensor integration for dead reckoning.
Define the term 'Mobile Ad-Hoc Network (MANET)' in the context of robotic search teams. Evaluate the performance of a MANET topology compared to a centralized star network topology for a swarm of rescue robots operating in deep subterranean cave networks where external communication infrastructure is absent.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
DEFINITION: A Mobile Ad-Hoc Network (MANET) is a self-configuring, infrastructureless wireless network of mobile nodes, where each node dynamically forwards data as a router. RELEVANCE TO SWARM ROBOTICS: It allows robots to communicate directly and relay messages to peer nodes, expanding the team's operational footprint beyond direct line-of-sight. COMPARATIVE EVALUATION: Centralized Star Topology: Relies on a single central base station. In deep subterranean environments, high-frequency radio signals are heavily attenuated by rock. If a robot moves around a sharp bend or deep into a tunnel, it completely loses connection (single point of failure). Range is limited to a single wireless hop. MANET Topology: Highly resilient. It supports multi-hop routing where robots act as intermediate repeaters, allowing data to snake around cave bends. If one robot fails, the network self-heals by routing data through alternative active nodes. However, MANETs introduce significant routing overhead, higher latency due to multiple hops, and potential bandwidth bottlenecks as the size of the swarm increases.
PastPaper.markingScheme
DEFINITION (2 Marks): Award 1 mark for identifying self-configuring or infrastructureless nature, and 1 mark for nodes acting as routing relays. RELEVANCE (1.5 Marks): Award 1.5 marks for explaining how this dynamically expands communication range for swarms. COMPARATIVE EVALUATION (4 Marks): Award 1.5 marks for evaluating Star topology limitations (attenuation, single point of failure), 1.5 marks for evaluating MANET advantages (multi-hop propagation, self-healing pathing), and 1 mark for identifying MANET limitations (latency, routing overhead).
Define 'semi-autonomous teleoperation' in search-and-rescue robotics. Evaluate how high network latency and high cognitive load impact a human operator driving a robot through unstable ruins, and explain how specific onboard control algorithms can alleviate these technical and human challenges.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
DEFINITION: Semi-autonomous teleoperation (shared control) is a control paradigm where human operators provide high-level directional commands or waypoint targets, while the robot's onboard control system executes low-level maneuvers autonomously, such as maintaining balance or avoiding obstacles. EVALUATION OF LATENCY & COGNITIVE LOAD: Network latency (caused by concrete barriers or wireless multi-hop delays) introduces a lag between operator action and video feedback. This causes 'move-and-wait' behaviors or overcorrection, where operators oversteer and crash the robot. High cognitive load arises from monitoring multiple sensor streams (video, thermals, tilt sensors) under high-stress conditions, leading to operator fatigue, slow decision-making, and compromised mission safety. ALGORITHMIC MITIGATION: 1. Local Reactive Obstacle Avoidance: An onboard collision-prevention algorithm can override human steering commands if an obstacle is detected within a threshold, preventing crashes regardless of lag. 2. Predictive Display Interfaces: On the operator's side, an algorithm projects a virtual 3D avatar of where the robot will be based on current velocity vectors, masking the latency. 3. Active Stabilization / Self-Righting: Onboard gyroscopic controllers automatically adjust track/wheel speeds to prevent flipping, removing the burden of manual stabilization from the operator.
PastPaper.markingScheme
DEFINITION (2 Marks): Award 1 mark for human specifying high-level goals/waypoints, and 1 mark for robot executing low-level reactive control. IMPACT EVALUATION (2.5 Marks): Award 1 mark for latency leading to overcorrection/crashes, 1 mark for cognitive load causing decision fatigue from multi-stream tracking, and 0.5 marks for slower overall mission speed. ALGORITHMIC SOLUTIONS (3 Marks): Award 1 mark per well-explained algorithm (max 3 marks), such as local obstacle avoidance overriding lag, predictive displays projecting future state, or active gyro stabilization reducing operator physical control demands.
Define 'sensor fusion' and explain how a state-estimation algorithm (like a Kalman Filter) or probabilistic framework (like Bayesian networks) is applied in rescue operations. Evaluate the trade-offs in reliability, power consumption, and computing overhead of using multi-modal sensor fusion (thermal, acoustic, and LiDAR) compared to relying on a single sensory input for victim localization.
PastPaper.showAnswersPastPaper.hideAnswers
PastPaper.workedSolution
DEFINITION: Sensor fusion is the centralized or decentralized processing of data from multiple sensors to generate an integrated output that contains less uncertainty than if the sensors were used individually. ALGORITHMIC EXECUTION: In a Kalman Filter, the algorithm operates in a two-step cycle: predict and update. It predicts the state vector \( x_k \) and covariance \( P_k \) based on a physical model, then updates these estimates using weighted sensory inputs (like LiDAR and IMU) based on their relative noise levels. In a Bayesian network, the conditional probability of a survivor's presence \( P(S | T, A) \) is updated as new independent evidence from thermal (\( T \)) and acoustic (\( A \)) sensors are processed, using Bayes' theorem to refine detection probability. EVALUATION: Reliability: Multi-modal fusion is highly robust; if smoke blinds the LiDAR, the acoustic and thermal sensors still operate. This drastically reduces false positives and negatives. Resource Trade-offs: However, running these algorithms in real-time requires high computational overhead (CPU/GPU load), which increases electrical power draw on the robot's battery, reducing mission runtime. It also adds payload weight (multiple sensors) and requires complex continuous calibration.
PastPaper.markingScheme
DEFINITION (1.5 Marks): Award 1.5 marks for combining multiple data sources to reduce observation uncertainty. ALGORITHMIC EXPLANATION (2 Marks): Award 2 marks for explaining either the predict-update cycle of the Kalman Filter (weighted estimation based on noise) or how Bayes' theorem updates the conditional probability of survivor presence given multi-sensor inputs. ADVANTAGES (2 Marks): Award 2 marks for robust multi-modal redundancy (preventing single-point sensor failures, reducing false search results in extreme environments). RESOURCE COSTS (2 Marks): Award 1 mark for computational overhead and reduced battery life, and 1 mark for physical payload constraints and calibration complexity.