2210/22/M/J/24 question 11: worked solution (May/June 2024, paper 22)
Show as plain textHide plain text
Cambridge O Level Computer Science 2210 · 8.2 Arrays Worked solution from the Programming Paper 2 Algorithms, Programming and Logic booklet, Part 2 of 3. Q55 2210/22/M/J/24 original Q11 Structured · 15 marks Worked solution Whole program Plan: clear the grid, put X in a random cell that is not Grid[1,1], then let the player move up to 10 times, checking each move stays inside the grid and whether X is found. // Clear every cell in the grid FOR Row ← 1 TO 5 FOR Column ← 1 TO 5 Grid[Row, Column] ← "" NEXT Column NEXT Row // Choose a random cell for X that is not Grid[1,1] REPEAT XRow ← ROUND(RANDOM() * 4 + 1, 0) XColumn ← ROUND(RANDOM() * 4 + 1, 0) UNTIL XRow <> 1 OR XColumn <> 1 Grid[XRow, XColumn] ← "X" // Player starts at top left with no moves used PlayerRow ← 1 PlayerColumn ← 1 NumberMoves ← 0 Win ← FALSE WHILE NumberMoves < 10 AND NOT Win OUTPUT "Move L (left), R (right), U (up) or D (down): " INPUT PlayerMove NewRow ← PlayerRow NewColumn ← PlayerColumn CASE OF UCASE(PlayerMove) "L" : NewColumn ← PlayerColumn - 1 "R" : NewColumn ← PlayerColumn + 1 "U" : NewRow ← PlayerRow - 1 "D" : NewRow ← PlayerRow + 1 OTHERWISE OUTPUT "Invalid move" ENDCASE // Only accept moves that stay inside the 5 by 5 grid IF NewRow < 1 OR NewRow > 5 OR NewColumn < 1 OR NewColumn > 5 THEN OUTPUT "That move is outside the grid. Try again." ELSE IF NewRow <> PlayerRow OR NewColumn <> PlayerColumn THEN PlayerRow ← NewRow PlayerColumn ← NewColumn NumberMoves ← NumberMoves + 1 // Check if the player has found the X IF Grid[PlayerRow, PlayerColumn] = "X" THEN OUTPUT "You Win" Win ← TRUE ENDIF ENDIF ENDIF ENDWHILE IF NOT Win THEN OUTPUT "You Lose" ENDIF All cells of Grid[] emptied using nested loops [1] Random row and column generated with RANDOM and ROUND [1] X placed in Grid[] and not in Grid[1,1] [1] Player start position (1,1) and move counter set [1] Loop that continues until X found or 10 moves used [1] Move input with a suitable message [1] Move left, right, up or down changes the row or column correctly [1] Move checked to be inside the grid, with an error message if not [1] Check whether the player is on the X, outputting You Win [1] Moves counted and You Lose output after 10 moves without finding X [1] Inputs and outputs have suitable messages [1] Comments explain how the code works (several useful comments) [2] Meaningful identifier names used (Grid and others) [1] Solution is in a logical order and meets all the requirements [1] Any correct pseudocode or program code that does the same job scores. Minor syntax errors are ignored. KEY IDEA Set up the grid, then loop: input a move, check it is inside the grid, update the position, test for X and count moves. TOTAL 15 marks Official mark scheme VIDEO ▶ Topic lesson A lesson on this topic · by Craig'n'Dave. Tap the picture to open it on YouTube.