An original Thinka practice paper modelled on the structure and difficulty of the Jun 2022 AQA A Level Computer Science 7517 paper. Not affiliated with or reproduced from AQA.
Paper 1 Section A
Answer all questions. Non-programmable theory questions, data structures, and algorithms.
12 Question · 39.95999999999999 marks
Question 1 · short_answer
3.33 marks
A programmer defines a Haskell function mystery as follows:
mystery :: [Int] -> Int mystery [] = 0 mystery (x:xs) | x `mod` 2 == 1 = x + mystery xs | otherwise = mystery xs
Trace the execution of mystery [4, 7, 2, 9, 3] and state the final return value.
Show answer & marking schemeHide answer & marking scheme
Worked solution
mystery [4, 7, 2, 9, 3] is evaluated as follows: - 4 is even, so mystery [7, 2, 9, 3] is called. - 7 is odd, so 7 + mystery [2, 9, 3] is evaluated. - 2 is even, so mystery [9, 3] is called. - 9 is odd, so 9 + mystery [3] is evaluated. - 3 is odd, so 3 + mystery [] is evaluated. - mystery [] returns 0.
Adding these up: 7 + 9 + 3 + 0 = 19.
Marking scheme
- 1 mark: Correctly trace that even numbers (4, 2) are ignored / skipped. - 1 mark: Show addition of odd numbers (7 + 9 + 3). - 1 mark: Correct final answer (19).
Question 2 · short_answer
3.33 marks
An arithmetic expression is written in infix notation: \((12 - 4) \times (5 + 3) \div 2\). Convert this expression into Reverse Polish (postfix) notation. Do not include any brackets in your answer.
Show answer & marking schemeHide answer & marking scheme
Worked solution
To convert \((12 - 4) \times (5 + 3) \div 2\) to Reverse Polish notation: 1. Convert the first brackets: (12 - 4) becomes 12 4 - 2. Convert the second brackets: (5 + 3) becomes 5 3 + 3. Multiply these two terms: 12 4 - 5 3 + * 4. Divide by 2: 12 4 - 5 3 + * 2 /
Marking scheme
- 1 mark: Correct conversion of brackets to '12 4 -' or '5 3 +'. - 1 mark: Correct ordering of multiplication '12 4 - 5 3 + *'. - 1 mark: Correct final expression '12 4 - 5 3 + * 2 /'.
Question 3 · short_answer
3.33 marks
A floating-point representation uses an 8-bit mantissa and a 4-bit exponent, both in two's complement. The following binary pattern represents a floating-point number: Mantissa: 10110000 Exponent: 0011 Calculate the denary equivalent of this floating-point representation. Show your working.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Convert the mantissa (two's complement): 10110000 binary represents a value of -1 * 2^0 + 0 * 2^-1 + 1 * 2^-2 + 1 * 2^-3 = -1 + 0.25 + 0.125 = -0.625. 2. Convert the exponent (two's complement): 0011 binary represents +3 in denary. 3. Multiply the mantissa by 2 raised to the exponent: -0.625 * 2^3 = -0.625 * 8 = -5.
Marking scheme
- 1 mark: Correctly converting the mantissa to -0.625 (or -5/8). - 1 mark: Correctly converting the exponent to 3. - 1 mark: Calculating the correct denary result of -5.
Question 4 · short_answer
3.33 marks
Simplify the following Boolean expression using Boolean algebra identities and rules: Q = A . B + A . (B + C) + B . (B + C) Show your working and state your final simplified expression.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Expand brackets: A . (B + C) = A . B + A . C and B . (B + C) = B . B + B . C = B + B . C. 2. Simplify B + B . C: using absorption law, B + B . C = B. 3. Substitute back: Q = A . B + A . B + A . C + B. 4. Simplify identical terms: A . B + A . B = A . B. Thus Q = A . B + A . C + B. 5. Combine terms with B: Q = B + A . B + A . C. Since B + A . B = B, we get Q = B + A . C.
Marking scheme
- 1 mark: Expand terms to obtain A . B + A . C + B . B + B . C. - 1 mark: Apply the absorption law or factorisation to simplify B . B + B . C to B. - 1 mark: Produce the correct final simplified expression B + A . C.
Question 5 · short_answer
3.33 marks
An array-based stack S of capacity 5 is initially empty. The pointer top is initialized to -1. The following operations are performed in order:
State the contents of the stack from bottom to top, and the final index value of top.
Show answer & marking schemeHide answer & marking scheme
Worked solution
- push 'K': Stack = [K], top = 0 - push 'R': Stack = [K, R], top = 1 - pop: returns R, Stack = [K], top = 0 - push 'M': Stack = [K, M], top = 1 - push 'P': Stack = [K, M, P], top = 2 - pop: returns P, Stack = [K, M], top = 1 - push 'W': Stack = [K, M, W], top = 2
Marking scheme
- 1 mark: Showing stack contents after first pop are [K] and top is 0. - 1 mark: Showing stack contents after second pop are [K, M] and top is 1. - 1 mark: Correct final stack [K, M, W] (bottom to top) and top pointer index 2.
Question 6 · short_answer
3.33 marks
A binary search tree (BST) is created by inserting the following keys in order: [50, 30, 70, 20, 40, 60, 80]. Perform a post-order traversal on the resulting tree and list the keys in the order they are visited.
Show answer & marking schemeHide answer & marking scheme
Worked solution
The BST structure is: - Root: 50 - Left subtree: 30 (left child 20, right child 40) - Right subtree: 70 (left child 60, right child 80)
Post-order traversal visits: Left, Right, Root. - Left child of 30 is 20. - Right child of 30 is 40. - Node 30 itself. - Left child of 70 is 60. - Right child of 70 is 80. - Node 70 itself. - Root node 50 itself. Order: 20, 40, 30, 60, 80, 70, 50.
Marking scheme
- 1 mark: Correctly sketching or representing the BST structure. - 1 mark: Correctly traversing the left subtree as 20, 40, 30. - 1 mark: Correctly listing the complete traversal: 20, 40, 30, 60, 80, 70, 50.
Question 7 · short_answer
3.33 marks
A regular expression is defined as: ^a(b|c)*d$. Identify which of the following five candidate strings are accepted by this regular expression: 'ad', 'abbcd', 'abcad', 'abcd', 'abd'.
Show answer & marking schemeHide answer & marking scheme
Worked solution
The regular expression specifies a string starting with 'a', followed by zero or more repetitions of 'b' or 'c' in any order, and ending with 'd'. - 'ad': accepted (0 occurrences of b/c). - 'abbcd': accepted ('b', 'b', 'c'). - 'abcad': rejected (contains 'a' in the middle). - 'abcd': accepted ('b', 'c'). - 'abd': accepted ('b').
Marking scheme
- 1 mark: Correctly identifying 'ad' and 'abd' as accepted. - 1 mark: Correctly identifying 'abbcd' and 'abcd' as accepted. - 1 mark: Correctly identifying 'abcad' as rejected.
Question 8 · short_answer
3.33 marks
A recursive algorithm is represented by the following pseudo-code function:
SUB routine(n, k) IF n < k THEN RETURN n ELSE RETURN routine(n - k, k) + 1 ENDIF ENDSUB
Trace the call routine(14, 4) and state the final integer value returned.
Show answer & marking schemeHide answer & marking scheme
- 1 mark: Correctly identifying the recursive calls made: routine(10,4), routine(6,4), and routine(2,4). - 1 mark: Correctly evaluating the base case routine(2,4) to 2. - 1 mark: Correctly calculating the final returned value of 5.
Question 9 · Short answer
3.33 marks
A programmer defines the following functional program in Haskell:
mystery :: [Int] -> Int mystery [] = 0 mystery (x:xs) | x `mod` 2 == 1 = x + mystery xs | otherwise = mystery xs - x
Calculate the exact integer output when the function call `mystery [3, 4, 5, 2]` is executed.
Show answer & marking schemeHide answer & marking scheme
1 mark for correctly evaluating mystery [] = 0 and mystery [2] = -2. 1 mark for correctly evaluating mystery [5, 2] = 3 and mystery [4, 5, 2] = -1. 1.33 marks for the final correct output of 2.
Question 10 · Short answer
3.33 marks
Evaluate the following Reverse Polish Notation (RPN) expression using a stack, showing the stack's state (with the top of the stack on the right) after each operator is processed:
8 3 - 4 * 6 2 / +
State the final evaluated value.
Show answer & marking schemeHide answer & marking scheme
Worked solution
We process the tokens from left to right: - Push 8, then 3. Stack: [8, 3] - Operator '-': Pop 3, Pop 8. Calculate 8 - 3 = 5. Push 5. Stack: [5] - Push 4. Stack: [5, 4] - Operator '*': Pop 4, Pop 5. Calculate 5 * 4 = 20. Push 20. Stack: [20] - Push 6, then 2. Stack: [20, 6, 2] - Operator '/': Pop 2, Pop 6. Calculate 6 / 2 = 3. Push 3. Stack: [20, 3] - Operator '+': Pop 3, Pop 20. Calculate 20 + 3 = 23. Push 23. Stack: [23]
Marking scheme
1 mark for correctly showing the intermediate stack state after first two operations [5] and [20]. 1 mark for correctly showing the intermediate stack state after division [20, 3]. 1.33 marks for the final correct value of 23.
Question 11 · Short answer
3.33 marks
A computer system represents floating-point numbers using a 12-bit format: an 8-bit normalized mantissa followed by a 4-bit exponent, both in two's complement representation. The binary representation is:
101100000011
Convert this representation into its decimal equivalent. Show your working.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Separate mantissa and exponent: - Mantissa: 10110000 - Exponent: 0011
2. Calculate the exponent: - Exponent is 0011 in binary, which is +3 in decimal.
3. Calculate the mantissa: - Mantissa is 1.0110000 in normalized binary fraction. - Since the sign bit is 1, it represents a negative number. - Converting 1.0110000 from two's complement: Weight of MSB is -1. Value = -1 * 1 + 0 * 0.5 + 1 * 0.25 + 1 * 0.125 = -1 + 0.375 = -0.625.
1 mark for correctly identifying the exponent as +3. 1 mark for correctly converting the mantissa to -0.625 (or showing equivalent correct fractional working). 1.33 marks for the final correct decimal value of -5.
Question 12 · Short answer
3.33 marks
A binary search tree has the following structure: - Root node is M - Left child of M is H, Right child of M is T - Left child of H is D, Right child of H is K - Left child of K is I - Right child of T is W - Left child of W is U
State the exact sequence of nodes visited in a post-order traversal of this tree, with node names separated by commas and spaces.
Show answer & marking schemeHide answer & marking scheme
Worked solution
A post-order traversal visits left subtree, right subtree, then the root node. - Left subtree of M is rooted at H: - Left subtree of H is D (leaf): visits D - Right subtree of H is rooted at K: - Left subtree of K is I (leaf): visits I - Right subtree of K is empty - Root of K subtree: visits K - Root of H subtree: visits H - So left subtree sequence: D, I, K, H - Right subtree of M is rooted at T: - Left subtree of T is empty - Right subtree of T is rooted at W: - Left subtree of W is U (leaf): visits U - Right subtree of W is empty - Root of W subtree: visits W - Root of T subtree: visits T - So right subtree sequence: U, W, T - Finally, root of the tree: visits M Combined sequence: D, I, K, H, U, W, T, M.
Marking scheme
1 mark for correctly traversing the left subtree (D, I, K, H). 1 mark for correctly traversing the right subtree (U, W, T). 1.33 marks for the complete correct sequence ending in M.
Paper 1 Section B
Write a complete new console application matching the specification and provide testing screen captures.
2 Question · 13 marks
Question 1 · Coding Task & Screenshot
6.5 marks
Write a complete Python, C#, or VB.Net console application that calculates and verifies a modulo-11 check digit for a 6-digit identification number. The program must: 1. Prompt the user to enter a 6-digit number. 2. If the user enters 'EXIT' (case-insensitive), the program terminates. 3. Validate that the input is exactly 6 digits. If not, output 'Invalid Input' and prompt again. 4. For a valid 6-digit input, calculate the check digit using these weights: Position 1 (leftmost) weight 7, Position 2 weight 6, Position 3 weight 5, Position 4 weight 4, Position 5 weight 3, Position 6 weight 2. 5. Sum the products of each digit multiplied by its weight. 6. Find the remainder when the sum is divided by 11. 7. Subtract the remainder from 11. If the result is 10, the check digit is 'X'. If the result is 11, the check digit is '0'. Otherwise, the check digit is the calculated single-digit value. 8. Output the final 7-character code (the original 6 digits followed by the check digit). 9. Test your program with inputs '410000' and '482015', and take a screenshot of your console output showing these test cases.
Show answer & marking schemeHide answer & marking scheme
Total Marks: 6.5 - 1.5 Marks: User input loop terminates correctly on 'EXIT' (case-insensitive) and validates that input is exactly a 6-digit numeric string. - 1.5 Marks: Correct implementation of the weighted sum multiplication algorithm using weights [7, 6, 5, 4, 3, 2]. - 2.0 Marks: Modulo-11 logic correctly handles remainder subtraction and maps 10 to 'X' and 11 to '0' as required. - 1.5 Marks: Screenshot evidence showing the program successfully receiving '410000' and '482015' as inputs and outputting '410000X' and '4820150' respectively.
Question 2 · Coding Task & Screenshot
6.5 marks
Write a complete Python, C#, or VB.Net console application that simulates a Circular Queue of fixed size 5. The program must: 1. Maintain a list/array of size 5 (initialized to empty/null values), and integer variables for 'front' pointer, 'rear' pointer, and 'size' (number of active elements). 2. Provide a loop that prompts the user to enter commands: 'ENQUEUE ', 'DEQUEUE', or 'EXIT' (case-insensitive). 3. If 'ENQUEUE' is called when the queue is full (size is 5), output 'Queue Full'. Otherwise, add the item to the rear pointer index (using circular wrapping), update the rear pointer, and increment size. 4. If 'DEQUEUE' is called when the queue is empty (size is 0), output 'Queue Empty'. Otherwise, retrieve the item at the front pointer index, update the front pointer (using circular wrapping), decrement size, and output the dequeued item. 5. After every operation, print the current state of the array, the front index, and the rear index. 6. Test your program by enqueuing 'A', 'B', 'C', then dequeuing once, then enqueuing 'D', and capture a screenshot of the console.
Show answer & marking schemeHide answer & marking scheme
Worked solution
Below is a complete implementation in Python:
queue = [None] * 5 front = 0 rear = 0 size = 0
while True: cmd = input('Enter command (ENQUEUE / DEQUEUE / EXIT): ').strip().split() if not cmd: continue op = cmd[0].upper() if op == 'EXIT': break elif op == 'ENQUEUE': if size == 5: print('Queue Full') else: val = cmd[1] queue[rear] = val rear = (rear + 1) % 5 size += 1 elif op == 'DEQUEUE': if size == 0: print('Queue Empty') else: val = queue[front] queue[front] = None front = (front + 1) % 5 size -= 1 print('Dequeued:', val) print(f'Queue: {queue} | Front Pointer: {front} | Rear Pointer: {rear} | Size: {size}')
Total Marks: 6.5 - 1.5 Marks: Circular Queue initialization of the array structure (size 5) and front, rear, and size management tracking. - 2.0 Marks: Correct circular pointer updates using modulo operations (`(index + 1) % 5`) for both enqueueing and dequeueing. - 1.5 Marks: Robust error handling displaying 'Queue Full' when size reaches 5 and 'Queue Empty' when size is 0. - 1.5 Marks: Screenshot evidence of the designated command sequence (Enqueue A, B, C, Dequeue, Enqueue D) confirming matching circular pointers and array outputs.
Paper 1 Section C
Answer questions concerning the provided skeleton program code and preliminary material without code adjustments.
4 Question · 10 marks
Question 1 · OOP Interpretation / Structured
2.5 marks
Refer to the skeleton class definitions provided below:
```text class Robot: private string Name private int XPosition private int YPosition private int BatteryLevel
public constructor Create(string RobotName, int StartX, int StartY) Name = RobotName XPosition = StartX YPosition = StartY BatteryLevel = 100
public virtual method Move(int DX, int DY) XPosition = XPosition + DX YPosition = YPosition + DY BatteryLevel = BatteryLevel - 5
public method GetBattery() returns int return BatteryLevel
class SecurityRobot inherits Robot: private int ShieldPower
public constructor Create(string RobotName, int StartX, int StartY, int StartShield) super.Create(RobotName, StartX, StartY) ShieldPower = StartShield
public override method Move(int DX, int DY) super.Move(DX, DY) ShieldPower = ShieldPower - 1 ```
Identify the method in SecurityRobot that demonstrates polymorphism through overriding, and explain how the constructor of SecurityRobot uses constructor chaining to initialise its inherited attributes.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Identifies 'Move' as the method overriding the parent method. (0.5 marks) 2. Explains that the keyword 'super' (or superclass reference) is used to call the base class constructor. (1.0 mark) 3. States that this passes the arguments RobotName, StartX, and StartY to initialize Name, XPosition, YPosition, and BatteryLevel attributes defined in Robot before the subclass-specific attribute ShieldPower is set. (1.0 mark)
Marking scheme
Max 2.5 marks: - 0.5 marks: Correctly naming the method Move. - 1.0 mark: Explains that super.Create (or calling the parent constructor) is used to invoke the parent class constructor. - 1.0 mark: Explains that this initializes the inherited attributes (Name, XPosition, YPosition, BatteryLevel) defined in the Robot superclass.
Question 2 · OOP Interpretation / Structured
2.5 marks
Referring to the class design of Robot in the provided skeleton code, explain how encapsulation is achieved and enforced. Your explanation must refer to the access modifiers used for the attributes and the role of the GetBattery method.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Mentions that the attributes (Name, XPosition, YPosition, BatteryLevel) are marked with the private access modifier, restricting external access. (1.0 mark) 2. Explains that access to these values is controlled through public methods. (0.5 marks) 3. Explains that GetBattery is a public getter (accessor) method that allows other classes to read the value of BatteryLevel without being able to modify it directly, thereby maintaining data integrity. (1.0 mark)
Marking scheme
Max 2.5 marks: - 1.0 mark: For identifying that attributes are declared as private to hide the inner state / prevent direct access from outside the class. - 0.5 marks: For stating that public methods are used as interfaces to access or modify private state. - 1.0 mark: For identifying GetBattery as a getter/accessor method providing read-only access to BatteryLevel and protecting it from unauthorized modification.
Question 3 · OOP Interpretation / Structured
2.5 marks
Assume an instance of SecurityRobot is created and used with the following code statements:
Determine the final state of MyBot by calculating the final values for the following four attributes: 1. XPosition 2. YPosition 3. BatteryLevel 4. ShieldPower
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Creation of MyBot: Name is set to "Sentry1", XPosition to 5, YPosition to 10. BatteryLevel is set to 100 in the parent constructor. ShieldPower is set to 20. 2. Execution of MyBot.Move(2, -3): - This calls the overridden Move(2, -3) in SecurityRobot. - SecurityRobot.Move first calls super.Move(2, -3). - super.Move(2, -3) updates: XPosition = 5 + 2 = 7; YPosition = 10 + (-3) = 7; BatteryLevel = 100 - 5 = 95. - SecurityRobot.Move then updates ShieldPower = 20 - 1 = 19.
Therefore, the final values are: - XPosition: 7 - YPosition: 7 - BatteryLevel: 95 - ShieldPower: 19
Marking scheme
Max 2.5 marks: - 0.5 marks: Correctly calculating XPosition as 7. - 0.5 marks: Correctly calculating YPosition as 7. - 0.5 marks: Correctly calculating BatteryLevel as 95. - 0.5 marks: Correctly calculating ShieldPower as 19. - 0.5 marks: Awarded for showing correct working indicating both the superclass and subclass method steps were executed.
Question 4 · OOP Interpretation / Structured
2.5 marks
A developer wants to implement a new class Fleet that acts as a collection of multiple Robot objects. The developer is deciding whether to use aggregation or composition.
Explain which of these two relationship types is more appropriate for the relationship between Fleet and Robot if individual robots can exist independently of a fleet, can be created before being assigned to any fleet, and can be reassigned to other fleets.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Selects Aggregation as the correct relationship. (0.5 marks) 2. Explains that aggregation represents an association where the lifetime of the contained objects (Robot) is not dependent on the container (Fleet) (i.e., a 'has-a' relationship with weak ownership). (1.0 mark) 3. Contrasts this with composition, where the lifetime of Robot would be strictly bound to Fleet (if Fleet is destroyed, its robots would also be destroyed), which violates the requirement that robots can exist independently and be transferred. (1.0 mark)
Marking scheme
Max 2.5 marks: - 0.5 marks: Explicitly selecting 'Aggregation' (or equivalent description of aggregation). - 1.0 mark: Explaining that under aggregation, the lifecycle of the Robot objects is independent of the Fleet object (destroying the Fleet does not destroy the Robots). - 1.0 mark: Explaining why composition is inappropriate (it would tightly couple lifecycles and prevent transfer or independent existence of robots).
Paper 1 Section D
Load the Breakthrough skeleton code. Implement programmatic updates and capture execution outputs.
4 Question · 37 marks
Question 1 · Interactive coding & Evidence
9.25 marks
In the Breakthrough skeleton code, players take turns moving pieces across a grid. You are required to implement a statistics tracking feature.
Modify the program to: 1. Declare and initialize variables to keep track of: - The total number of valid moves made by Player 1 and Player 2. - The total number of successful captures made by Player 1 and Player 2. 2. Increment these variables appropriately in the game loop or move execution method when a valid move or capture occurs. 3. At the end of the game, output a formatted summary of these statistics: - Player 1: [Moves] moves, [Captures] captures (Capture Rate: [Rate]%) - Player 2: [Moves] moves, [Captures] captures (Capture Rate: [Rate]%) Note: The Capture Rate is calculated as: \(\text{Capture Rate} = \frac{\text{captures}}{\text{moves}} \times 100\) (formatted to 1 decimal place. If moves = 0, rate is 0.0%).
Provide: - The modified source code segments showing where variables are declared, updated, and displayed. - The console output showing the final stats screen after Player 1 made 5 moves with 2 captures, and Player 2 made 4 moves with 1 capture.
Show answer & marking schemeHide answer & marking scheme
- 2 marks: Correctly declaring and initializing tracking variables for both players. - 3 marks: Correctly incrementing moves and captures in the appropriate location in code. - 2 marks: Correctly calculating capture rate with guard against division-by-zero, formatted to 1 decimal place. - 2.25 marks: Accurate test output matching the requested scenario.
Question 2 · Interactive coding & Evidence
9.25 marks
In the standard Breakthrough game, a piece can move one square forward either straight or diagonally. However, strict rules dictate that: 1. A diagonal move is ONLY valid if it results in capturing an opponent's piece (the destination square must contain an opponent's piece). 2. A straight forward move is ONLY valid if the destination square is empty.
Modify the validation method (typically `IsValidMove` or `CheckMoveIsValid`) in the skeleton code to enforce these strict rules.
Provide: - The modified validation code. - A written description of two test cases you would run to prove the code works, stating the inputs used and the expected output boolean (True/False).
Show answer & marking schemeHide answer & marking scheme
# Determine direction of player movement # (Assuming Player 1 moves down (+1) and Player 2 moves up (-1)) Direction = 1 if self.__CurrentPlayer == 1 else -1
Test Cases: 1. Test Case 1 (Diagonal No Capture): - Start: (3, 3) containing Player 1 piece. End: (4, 4) which is empty. - Expected output: False (invalid because diagonal move target is empty). 2. Test Case 2 (Straight Capture Attempt): - Start: (3, 3) containing Player 1 piece. End: (4, 3) containing Player 2 piece. - Expected output: False (invalid because straight move target is not empty).
Marking scheme
- 3 marks: Ensuring straight-forward moves are only valid if target tile is empty. - 3 marks: Ensuring diagonal moves are only valid if target tile contains an opponent's piece. - 3.25 marks: Providing two complete test cases with clear inputs, expected boolean outputs, and reasoning.
Question 3 · Interactive coding & Evidence
9.25 marks
A classic feature for strategy games is the ability to undo the last move. Modify the Breakthrough skeleton code to implement a move history undo stack: 1. Initialize a stack to store the history of board states (you may use a standard list as a stack or a custom Stack class). 2. Before any valid move is made, push a deep copy of the current board state onto the stack. 3. Allow the player to input 'UNDO' during their turn input. 4. If 'UNDO' is entered, pop the previous state and restore the board to this state, then toggle the active player back to the previous player. If the stack is empty, display an error message 'No moves to undo!'.
Provide: - The code modifications showing stack initialization, state copying/pushing, and the undo mechanism. - The console output showing the error message when 'UNDO' is entered at the very start of the game.
Show answer & marking schemeHide answer & marking scheme
2. Pushing state before a move: ```python def MakeMove(self, ...): # Save current state BoardCopy = copy.deepcopy(self.__Board) self.__HistoryStack.append((BoardCopy, self.__CurrentPlayer)) # ... apply move ... ```
Console output at start of game: Command: UNDO No moves to undo!
Marking scheme
- 2 marks: Correctly importing `copy` and initializing an empty list/stack for history. - 3 marks: Performing a deep copy of the board and pushing it alongside player turn information onto the stack before each valid move. - 3 marks: Correctly popping, restoring the board grid, reverting the active player, and handling the empty stack check. - 1.25 marks: Correct console output showing the 'No moves to undo!' message when starting game.
Question 4 · Interactive coding & Evidence
9.25 marks
To add strategic depth, we want to place physical barriers on the board that neither player can move onto. Modify the Breakthrough program to: 1. In the board setup phase, randomly place exactly three obstacle tiles, represented by the character '#', in the middle two rows (rows index 3 and 4 of an 8x8 board). 2. Ensure that obstacles do not overwrite any pre-existing player pieces. 3. Modify the move validation method so that a move targeting an obstacle tile ('#') is immediately declared invalid.
Provide: - The modified board initialization code. - The modified move validation code. - An ASCII visualization or description of an 8x8 board layout with three randomly placed '#' obstacles in the middle rows.
Show answer & marking schemeHide answer & marking scheme
Worked solution
Implementation details:
1. Modify Board Setup: ```python import random # After setting up starting pieces for both players: ObstaclesPlaced = 0 while ObstaclesPlaced < 3: Row = random.randint(3, 4) Col = random.randint(0, 7) if self.__Board[Row][Col] == ' ': self.__Board[Row][Col] = '#' ObstaclesPlaced += 1 ```
2. Modify Validation Logic: ```python def IsValidMove(self, StartRow, StartCol, EndRow, EndCol): # ... standard checks ... if self.__Board[EndRow][EndCol] == '#': return False # ... rest of validation ... ```
- 3 marks: Correctly placing exactly 3 obstacles in middle rows (3 and 4) randomly and ensuring no player pieces are overwritten. - 3 marks: Adding validation to ensure moves to a target containing '#' are invalid. - 3.25 marks: Clear sample ASCII representation of the board demonstrating the 3 obstacles correctly positioned in the middle rows.
Paper 2 Section A
Answer all questions. Computational math, architecture, databases, regular expressions, and software systems.
16 Question · 99.9 marks
Question 1 · Logical / Conversion Problems
5.86 marks
A computer system uses a 12-bit normalized two's complement floating-point representation, where the first 8 bits are the mantissa (including the sign bit) and the remaining 4 bits are the exponent (also in two's complement).
Convert the denary value \(-6.75\) into this floating-point representation. Show your working.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Convert the absolute denary value \(6.75\) to binary: \(6.75 = 4 + 2 + 0.5 + 0.25 = 110.11_{2}\).
2. Represent \(-6.75\) in two's complement with sufficient headroom: Start with positive value: \(0110.1100_{2}\) Invert the bits: \(1001.0011_{2}\) Add 1: \(1001.0100_{2}\) (This represents \(-8 + 1 + 0.25 = -6.75\)).
3. Normalize the binary number. A negative normalized floating-point number must start with bits `10`: Our binary value is \(1001.0100\). To format this with the binary point after the first bit (sign bit), we write it as \(1.0010100\). Moving the binary point 3 places to the left means we must multiply by \(2^{3}\) to maintain the value: \(1.0010100 \times 2^{3}\).
4. Extract Mantissa and Exponent: - Mantissa (8 bits): `10010100` - Exponent (4 bits): \(3\) in binary is `0011`.
5. Combine to form the 12-bit representation: `100101000011`.
Marking scheme
- **1 Mark**: Correctly converting positive \(6.75\) to binary (\(110.11\)). - **2 Marks**: Correctly converting to negative fixed-point two's complement (\(1001.0100\)). - **1.5 Marks**: Correct normalization of mantissa to 8 bits (\(10010100\)). - **1.36 Marks**: Correct exponent representation of \(3\) in 4 bits (\(0011\)) resulting in final correct 12-bit answer: `100101000011`.
Question 2 · Logical / Conversion Problems
5.86 marks
Simplify the following Boolean expression using Boolean algebraic identities and De Morgan's laws:
Show answer & marking schemeHide answer & marking scheme
Worked solution
Step 1: Simplify the first term \(\overline{\overline{A \cdot B} + C}\) using De Morgan's Law: \(\overline{\overline{A \cdot B}} \cdot \overline{C} = (A \cdot B) \cdot \overline{C} = A \cdot B \cdot \overline{C}\).
Step 2: Simplify the second term \(\overline{B \cdot \overline{C}}\) using De Morgan's Law: \(\overline{B} + \overline{\overline{C}} = \overline{B} + C\).
Step 3: Combine the simplified terms: \(Q = (A \cdot B \cdot \overline{C}) \cdot (\overline{B} + C)\).
Step 4: Distribute the terms: \(Q = (A \cdot B \cdot \overline{C} \cdot \overline{B}) + (A \cdot B \cdot \overline{C} \cdot C)\).
Step 5: Apply the Complement Law (\(X \cdot \overline{X} = 0\)): Since \(B \cdot \overline{B} = 0\), the first term becomes \(A \cdot 0 \cdot \overline{C} = 0\). Since \(\overline{C} \cdot C = 0\), the second term becomes \(A \cdot B \cdot 0 = 0\).
Step 6: Combine results: \(Q = 0 + 0 = 0\).
Marking scheme
- **2 Marks**: Correct application of De Morgan's Law on the first term to get \(A \cdot B \cdot \overline{C}\). - **1.5 Marks**: Correct application of De Morgan's Law on the second term to get \(\overline{B} + C\). - **1.5 Marks**: Correctly distributing the expression to show products containing \(B \cdot \overline{B}\) and \(C \cdot \overline{C}\). - **0.86 Marks**: Correct final simplification to `0` (or `False`).
Question 3 · Logical / Conversion Problems
5.86 marks
A regular expression is defined as:
`^([a-z]{2}\d[A-Z]?|test_\d{3})$`
Identify which of the following five strings are valid matches for this regular expression. State the number of each matching string and explain your reasoning for each.
Show answer & marking schemeHide answer & marking scheme
Worked solution
Let us analyze the regular expression structure. It consists of two alternatives separated by the `|` symbol: - Alternative 1: `[a-z]{2}\d[A-Z]?` requires exactly 2 lowercase letters, followed by exactly 1 digit, and optionally 1 uppercase letter. - Alternative 2: `test_\d{3}` requires the literal string `test_` followed by exactly 3 digits.
Now we evaluate each string: 1. `ab3`: Matches Alternative 1. `ab` (2 lowercase letters), `3` (1 digit), and no trailing uppercase letter (since it is optional). **Valid** 2. `xy4W`: Matches Alternative 1. `xy` (2 lowercase letters), `4` (1 digit), and `W` (1 uppercase letter). **Valid** 3. `test_10`: Fails both. It starts with `test_` but has only 2 digits (`10`), not 3. **Invalid** 4. `test_952`: Matches Alternative 2. Literal `test_` followed by exactly 3 digits (`952`). **Valid** 5. `a1B`: Fails both. It only has 1 lowercase letter (`a`) instead of the required 2 for Alternative 1. **Invalid**
The matching strings are 1, 2, and 4.
Marking scheme
- **2 Marks**: For correctly identifying string 1 as a match and explaining why (optional uppercase matches). - **1.5 Marks**: For correctly identifying string 2 as a match and explaining why. - **1.5 Marks**: For correctly identifying string 4 as a match and explaining why (exactly three digits constraint). - **0.86 Marks**: For identifying strings 3 and 5 as non-matches with valid reasons.
Question 4 · Logical / Conversion Problems
5.86 marks
Convert the following infix expression to Reverse Polish Notation (RPN) and show the step-by-step stack evaluation to find the final result:
\[ (12 - 4) \times 3 + 16 / 4 \]
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Convert Infix to RPN: - Evaluate parentheses first: `(12 - 4)` becomes `12 4 -`. - Multiply by 3: `12 4 - 3 *`. - Next, process `16 / 4`: `16 4 /`. - Finally, add the two parts: `12 4 - 3 * 16 4 / +`.
Write an SQL query to retrieve the `FirstName`, `LastName`, and the sum of `TotalAmount` (aliased as `TotalSpent`) for all customers from the `Country` 'UK'. The results should be grouped by the customer's first name and last name, and only include records where their total sum of spending is strictly greater than 150.
Show answer & marking schemeHide answer & marking scheme
Worked solution
To implement this query, we need to join both tables and filter by country, group by name, and then apply a filter on the aggregated sum:
```sql SELECT Customer.FirstName, Customer.LastName, SUM(Orders.TotalAmount) AS TotalSpent FROM Customer INNER JOIN Orders ON Customer.CustomerID = Orders.CustomerID WHERE Customer.Country = 'UK' GROUP BY Customer.FirstName, Customer.LastName HAVING SUM(Orders.TotalAmount) > 150; ```
Marking scheme
- **1.5 Marks**: Correctly selecting the columns `Customer.FirstName`, `Customer.LastName` and establishing the aggregate `SUM(Orders.TotalAmount) AS TotalSpent`. - **1.5 Marks**: Correct implementation of the `INNER JOIN` (or implicit join) linking `Customer` and `Orders` on `CustomerID`. - **1 Mark**: Correct `WHERE` clause filtering by `Customer.Country = 'UK'`. - **1 Mark**: Correct `GROUP BY` clause on both `Customer.FirstName` and `Customer.LastName`. - **0.86 Marks**: Correct `HAVING` clause containing `SUM(Orders.TotalAmount) > 150` (Note: using the alias in HAVING is invalid in standard ANSI SQL, so the aggregate function must be used).
1. Calculate the dot product \(\mathbf{u} \cdot \mathbf{v}\). 2. Determine, with a mathematical reason, whether the angle between the two vectors is acute, obtuse, or right-angled.
Show answer & marking schemeHide answer & marking scheme
2. Relationship to the angle: The dot product is related to the angle \(\theta\) between two vectors by the equation: \[ \mathbf{u} \cdot \mathbf{v} = |\mathbf{u}| |\mathbf{v}| \cos(\theta) \] Since the dot product is exactly \(0\), and neither vector is a zero vector, \(\cos(\theta) = 0\), which means \(\theta = 90^\circ\) (or \(\pi/2\) radians). Thus, the angle is right-angled (orthogonal).
Marking scheme
- **3 Marks**: Correct step-by-step arithmetic to calculate the dot product value of `0`. - **1.5 Marks**: Correctly identifying that the vectors are right-angled / orthogonal. - **1.36 Marks**: Clear mathematical justification referring to \(\cos(\theta) = 0\) or the property that a dot product of zero indicates perpendicularity.
Question 7 · Logical / Conversion Problems
5.86 marks
An organization is assigned the IPv4 subnet block `192.168.16.0/22`.
1. Convert the `/22` prefix length notation into a standard dotted-decimal subnet mask. 2. Calculate the maximum number of usable host IP addresses available on this subnet.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Convert `/22` to a subnet mask: A `/22` prefix means the first 22 bits of the subnet mask are set to 1, and the remaining 10 bits are set to 0. - First octet: `11111111` = 255 - Second octet: `11111111` = 255 - Third octet: `11111100` = 252 (since \(128 + 64 + 32 + 16 + 8 + 4 = 252\)) - Fourth octet: `00000000` = 0 Resulting subnet mask: `255.255.252.0`.
2. Calculate usable host IP addresses: - The total number of bits in an IPv4 address is 32. - Host bits = \(32 - 22 = 10\). - Total possible IP addresses = \(2^{10} = 1024\). - Subtract 2 for the network address (all host bits 0) and the directed broadcast address (all host bits 1). - Usable host IP addresses = \(1024 - 2 = 1022\).
Marking scheme
- **3 Marks**: Correct binary expansion and calculation of the dotted-decimal subnet mask `255.255.252.0` (award 1 mark per correct octet starting from the third). - **2 Marks**: Correct calculation of host bits (10) and total addresses (1024). - **0.86 Marks**: Correctly subtracting 2 to give the final usable host count of `1022`.
Question 8 · Logical / Conversion Problems
5.86 marks
In an assembly language instruction set, Register 1 (`R1`) contains the 8-bit binary value `00111100` and Register 2 (`R2`) contains the 8-bit binary value `01011010`.
Perform the following operations sequentially and state the final 8-bit binary value left in register `R1`: 1. `AND R3, R1, R2` (Bitwise AND of R1 and R2, store in R3) 2. `LSL R4, R3, #2` (Logical Shift Left of R3 by 2 positions, store in R4) 3. `ORR R1, R4, R2` (Bitwise OR of R4 and R2, store in R1)
Show your working for each step.
Show answer & marking schemeHide answer & marking scheme
Worked solution
Let's perform the operations step-by-step:
1. **Step 1: Bitwise AND** (`AND R3, R1, R2`) - `R1`: `0011 1100` - `R2`: `0101 1010` - Perform AND on each column: ``` 0011 1100 AND 0101 1010 ------------- 0001 1000 (R3) ```
2. **Step 2: Logical Shift Left by 2** (`LSL R4, R3, #2`) - `R3`: `0001 1000` - Shift left by 2 bits, padding with zeros on the right: - Shift 1: `0011 0000` - Shift 2: `0110 0000` - `R4` value: `0110 0000`
3. **Step 3: Bitwise OR** (`ORR R1, R4, R2`) - `R4`: `0110 0000` - `R2`: `0101 1010` - Perform OR on each column: ``` 0110 0000 OR 0101 1010 ------------- 0111 1010 (R1) ```
Final 8-bit binary value in `R1` is `01111010`.
Marking scheme
- **2 Marks**: Correctly performing the bitwise AND operation to get R3 = `00011000`. - **2 Marks**: Correctly performing the logical shift left by 2 positions to get R4 = `01100000`. - **1.86 Marks**: Correctly performing the final bitwise OR operation to get R1 = `01111010`.
Question 9 · conversion
5.86 marks
A computer system represents floating-point numbers using a 12-bit two's complement format: an 8-bit normalized mantissa followed by a 4-bit exponent. Convert the binary representation \(10101000\,0011\) into its denary equivalent. Show all steps of your working.
Show answer & marking schemeHide answer & marking scheme
Worked solution
The mantissa is \(10101000_2\). Since it is in two's complement, the MSB has a value of \(-1\). Mantissa = \(-1 + 0.25 + 0.0625 = -0.6875\). The exponent is \(0011_2\) which represents \(+3\) in denary. Therefore, the value is calculated as \(-0.6875 \times 2^3 = -0.6875 \times 8 = -5.5\).
Marking scheme
[1 Mark] Identifying the exponent as +3. [1 Mark] Identifying the mantissa MSB as representing -1. [1 Mark] Showing the correct fractional values of the mantissa (0.25 and 0.0625). [1 Mark] Correct calculation of the mantissa as -0.6875. [1.86 Marks] Correct final denary value of -5.5.
Question 10 · conversion
5.86 marks
Simplify the Boolean expression \((A \cdot B) + (A \cdot (B + C)) + B \cdot (B + C)\) to its simplest Sum of Products (SOP) form. Show each step of your simplification, identifying the Boolean identities used.
Show answer & marking schemeHide answer & marking scheme
Worked solution
1. Expand the terms: \(A \cdot B + A \cdot B + A \cdot C + B \cdot B + B \cdot C\). 2. Apply the Idempotent Law (\(A \cdot B + A \cdot B = A \cdot B\) and \(B \cdot B = B\)) to get: \(A \cdot B + A \cdot C + B + B \cdot C\). 3. Apply the Absorption Law (\(B + B \cdot C = B\)) to get: \(A \cdot B + A \cdot C + B\). 4. Apply the Absorption Law again (\(B + A \cdot B = B\)) to get the final simplified expression: \(B + A \cdot C\).
Marking scheme
[1 Mark] Correct expansion of the initial expression terms. [1 Mark] Application of the Idempotent Law to simplify terms. [1 Mark] Application of the Absorption Law to simplify B + B.C. [1 Mark] Application of the Absorption Law to simplify B + A.B. [1.86 Marks] Correct final simplified expression (accept B + AC).
Question 11 · conversion
5.86 marks
A router is configured with an IP address of \(192.168.75.142\) and a subnet mask of \(255.255.255.224\). Calculate the Network Identifier (network address) in dotted decimal format by converting the host portion and performing the appropriate bitwise logical operation. Show your working.
Show answer & marking schemeHide answer & marking scheme
Worked solution
The first three octets of the subnet mask are 255, so the network prefix remains \(192.168.75\). For the fourth octet: \(142\) in binary is \(10001110_2\). The mask \(224\) in binary is \(11100000_2\). Performing a bitwise AND operation: \(10001110 \text{ AND } 11100000 = 10000000_2\), which is \(128\) in denary. Combining these gives the network address of \(192.168.75.128\).
Marking scheme
[1 Mark] Correct conversion of host octet 142 to binary (10001110). [1 Mark] Correct conversion of mask octet 224 to binary (11100000). [1 Mark] Stating that a bitwise AND operation is performed between the host and mask. [1 Mark] Correctly calculating the resulting binary octet as 10000000. [1.86 Marks] Correct final dotted decimal address: 192.168.75.128.
Question 12 · conversion
5.86 marks
Convert the infix arithmetic expression \(((A + B) * (C - D)) / (E + F)\) into Reverse Polish Notation (postfix format). Show the order of operations by outlining intermediate steps.
Show answer & marking schemeHide answer & marking scheme
Worked solution
Convert individual parenthesized sub-expressions first: \((A + B) \rightarrow A\,B\,+\), \((C - D) \rightarrow C\,D\,-\), and \((E + F) \rightarrow E\,F\,+\). Next, apply the multiplication operator to the first two results: \((A\,B\,+) * (C\,D\,-) \rightarrow A\,B\,+\,C\,D\,-\,*\). Finally, apply the division operator with the third result: \((A\,B\,+\,C\,D\,-\,*) / (E\,F\,+) \rightarrow A\,B\,+\,C\,D\,-\,*\,E\,F\,+\,/\).
Marking scheme
[1 Mark] Converting (A + B) to postfix (AB+). [1 Mark] Converting (C - D) to postfix (CD-) and (E + F) to postfix (EF+). [1 Mark] Correctly applying the multiplication operator to get AB+CD-*. [1 Mark] Correctly placing the division operator at the end. [1.86 Marks] Fully correct final Reverse Polish Notation expression: A B + C D - * E F + /
Question 13 · conversion
5.86 marks
Calculate the dot product of the two 3-dimensional vectors \(\mathbf{a} = [5, -2, 4]\) and \(\mathbf{b} = [-3, 6, 1]\). Show all calculations.
Show answer & marking schemeHide answer & marking scheme
[1 Mark] Recalling or demonstrating the correct dot product formula. [1 Mark] Calculating the product of the first elements as -15. [1 Mark] Calculating the product of the second elements as -12. [1 Mark] Calculating the product of the third elements as 4. [1.86 Marks] Correct final summed integer value of -23.
Question 14 · conversion
5.86 marks
An 8-bit register contains the binary pattern \(01101100_2\) (Register 1) and another contains \(10101010_2\) (Register 2). The processor executes an assembly instruction: \(\text{AND } R3, R1, R2\) followed by \(\text{LSL } R4, R3, \#2\). Convert the final state of Register 4 into its 8-bit binary equivalent. Show each stage of your trace.
Show answer & marking schemeHide answer & marking scheme
Worked solution
Stage 1: Perform the bitwise AND of R1 (01101100) and R2 (10101010), which yields R3 = 00101000. Stage 2: Perform Logical Shift Left (LSL) by 2 bits on R3. Shifting 00101000 left by 2 positions yields R4 = 10100000, with zeroes padded on the right.
Marking scheme
[1 Mark] Correctly calculating the first half of the AND operation. [1 Mark] Correctly calculating the second half of the AND operation. [1 Mark] Identifying R3 as 00101000. [1 Mark] Correctly shifting the bits left by 2 positions. [1.86 Marks] Providing the correct final 8-bit binary string: 10100000.
Question 15 · conversion
5.86 marks
A database table \(\text{StudentEnrollment}(\underline{\text{StudentID}}, \underline{\text{CourseID}}, \text{CourseName}, \text{Instructor}, \text{Grade})\) is currently in First Normal Form (1NF). The primary key is the composite key (StudentID, CourseID). Convert this relation into Second Normal Form (2NF) relations to resolve partial dependencies. Write your answer by listing the new table schemas in the format: TableName(PrimaryKey, NonKeys...).
Show answer & marking schemeHide answer & marking scheme
Worked solution
In 1NF, CourseName and Instructor depend only on CourseID (part of the composite key), which represents a partial key dependency. To convert to 2NF, we remove these attributes into a new relation. This results in: 1. \(\text{StudentGrade}(\underline{\text{StudentID}}, \underline{\text{CourseID}}, \text{Grade})\) and 2. \(\text{Course}(\underline{\text{CourseID}}, \text{CourseName}, \text{Instructor})\).
Marking scheme
[1 Mark] Identifying that CourseName and Instructor have a partial key dependency. [1 Mark] Defining the StudentGrade relation with the composite primary key. [1 Mark] Including Grade in the StudentGrade relation as it depends on both keys. [1 Mark] Defining the Course relation with CourseID as its primary key. [1.86 Marks] Listing both fully correct 2NF table schemas with keys correctly indicated.
Question 16 · essay
12 marks
A national ticket-booking agency is upgrading its database system to handle extremely high volumes of concurrent transactions during major concert ticket releases. Currently, the system experiences issues such as double-booking (where two customers are allocated the exact same seat) and lost reservation records if a database server crashes mid-booking.
Discuss how the database administrators can use ACID (Atomicity, Consistency, Isolation, Durability) properties and record locking to ensure data integrity and prevent concurrency issues.
In your answer you should: - Explain how each of the four ACID properties applies directly to this ticketing scenario. - Describe how concurrent transaction conflicts (such as the 'lost update' problem) occur and how record locking (including shared and exclusive locks) can resolve them. - Discuss the potential operational challenges introduced by record locking (such as deadlocks) and how the system might mitigate or resolve these issues.
Show answer & marking schemeHide answer & marking scheme
Worked solution
### Part 1: ACID Properties in the Ticketing Scenario - **Atomicity**: This ensures that all operations within a ticket booking transaction are treated as a single, indivisible unit of work. For instance, the sequence of reserving seat 12B, processing the payment, and sending the confirmation email must either complete in its entirety or not happen at all. If the payment fails mid-way, Atomicity ensures the seat reservation is rolled back, preventing orphaned 'reserved' seats that have not been paid for. - **Consistency**: This ensures that a transaction can only transition the database from one valid state to another, maintaining all predefined schema rules and constraints. In this scenario, a consistency rule might be: 'A seat cannot have more than one paid ticket associated with it.' If a transaction attempts to write a second ticket for seat 12B, the database system must reject the transaction to preserve consistency. - **Isolation**: In a highly concurrent environment, many users are booking tickets simultaneously. Isolation ensures that concurrent transactions execute as if they were running sequentially. For example, while Customer A's transaction is actively processing the payment for seat 12B, Customer B's query should not be able to read that seat as 'available' or 'partially reserved' until Customer A's transaction is fully committed or rolled back. - **Durability**: Once a ticket reservation transaction is confirmed and committed, the changes are written to non-volatile storage (such as solid-state drives with transactional logging). If the database server suffers a sudden power failure or crash immediately after the customer receives their confirmation screen, Durability guarantees that their booking is not lost when the server boots back up.
### Part 2: Concurrency Conflicts and Record Locking - **The Lost Update Problem**: This occurs when two transactions read the same data concurrently, modify it, and write it back. For example: 1. Customer A reads seat 12B status (Available). 2. Customer B reads seat 12B status (Available). 3. Customer A marks seat 12B as 'Reserved' and saves. 4. Customer B marks seat 12B as 'Reserved' and saves, overwriting Customer A's update. Both customers believe they have booked the seat. - **How Record Locking Resolves This**: When a transaction begins modifying a record, a lock is applied, blocking other transactions from accessing that record until the lock is released. - **Shared Locks (Read Locks)**: Multiple transactions can hold a shared lock on a record simultaneously, allowing them to read the seat's status (e.g., multiple users checking seat availability). However, no transaction can write to or modify the record while a shared lock exists. - **Exclusive Locks (Write Locks)**: When a transaction wishes to update the seat status to 'Reserved', it must acquire an exclusive lock. Only one transaction can hold an exclusive lock on a record at a time. It prevents any other transactions from reading or writing to that record. If Customer A acquires an exclusive lock on seat 12B, Customer B's transaction must wait until Customer A's transaction finishes and releases the lock.
### Part 3: Operational Challenges (Deadlocks and Mitigations) - **The Deadlock Problem**: Extensive use of exclusive record locking can lead to deadlocks. This occurs when two or more transactions are waiting for each other to release locks. For example: - Transaction 1 locks Seat A and requests a lock on Seat B. - Transaction 2 locks Seat B and requests a lock on Seat A. Neither transaction can proceed, causing the system to freeze or hang indefinitely. - **Deadlock Mitigation and Resolution Strategies**: - **Deadlock Detection**: The database engine runs background processes to construct a resource allocation graph. If a cycle (loop) is detected, the database engine aborts one of the transactions (the 'victim'), rolls back its changes, releases its locks, and allows the other transaction to complete. - **Deadlock Prevention (Lock Ordering)**: The system can require all transactions to lock resources in a strictly defined, sequential order (e.g., always lock seats in alphabetical/numerical order: Seat A first, then Seat B). If Transaction 2 is forced to lock Seat A before Seat B, the deadlock situation cannot arise. - **Lock Timeouts**: Every lock request is given a maximum wait time (timeout). If Transaction 1 cannot acquire the lock on Seat B within 5 seconds, it aborts, releases its lock on Seat A, and retries later, preventing a permanent freeze.
Marking scheme
### Level of Response marking grid:
- **Level 3 (9-12 marks)**: The candidate provides a detailed, coherent, and highly technical response. All four ACID properties are clearly explained and accurately applied to the ticket booking system. The mechanics of the lost update problem and record locking (clearly distinguishing shared and exclusive locks) are accurately described. The deadlock scenario is correctly explained, and at least two practical mitigation/prevention methods (e.g., lock ordering, detection/rollback, or timeouts) are analyzed. Technical vocabulary is used correctly throughout. - **Level 2 (5-8 marks)**: The candidate provides a mostly structured response. At least three ACID properties are correctly explained with some application to the context. Record locking and its role in resolving concurrency issues is understood, though the distinction between shared and exclusive locks may be weak or incomplete. The candidate identifies deadlocks but provides limited explanation of mitigation strategies. - **Level 1 (1-4 marks)**: The candidate provides a basic or superficial response. They may define some ACID terms in isolation without clear application to the scenario. There is a primitive understanding of locking (e.g., 'it stops others from using it') but lacks technical detail. Deadlocks may be mentioned but without clear explanation or resolution.
### Indicative Content: - **Atomicity**: Complete transaction or nothing; tickets aren't charged without being booked. - **Consistency**: Preserves database rules; no double booking of the exact same primary key/seat. - **Isolation**: Concurrent transactions do not interfere; temporary states are invisible. - **Durability**: Commits survive crashes; saved to non-volatile disk logs. - **Lost Update**: Interleaved read-modify-write sequences leading to overwritten data. - **Shared Locks**: Multi-reader, zero-writer block. - **Exclusive Locks**: Single-writer, zero-reader block. - **Deadlock**: Circular wait conditions (T1 waits for T2, T2 waits for T1). - **Deadlock Solutions**: Deadlock detection & rollback, lock ordering, or lock timeouts.
Wondering how well you actually know this?
Thinka is an AI practice app for DSE students — unlimited questions, instant auto-marking, and detailed step-by-step solutions. 100,000+ students use it to confirm they actually know it, not just think they do.