Worked solution from the Data Types and Structures Paper 2 Problem-solving and Programming booklet, Part 3 of 4.
Search the array until an unassigned character with the right role is found or all 45 have been checked. When found, assign the player and stop the search. Then output the right message.
PROCEDURE Assign(ThisPlayer : INTEGER, ThisRole : STRING)
DECLARE Index : INTEGER
DECLARE Done : BOOLEAN
Done ← FALSE
Index ← 1
WHILE Index <= 45 AND Done = FALSE
IF Character[Index].Player = 0 AND Character[Index].Role = ThisRole THEN
Character[Index].Player ← ThisPlayer
Done ← TRUE
ELSE
Index ← Index + 1
ENDIF
ENDWHILE
IF Done = TRUE THEN
OUTPUT Character[Index].Name, " the ", Character[Index].Role, " has been assigned to player ", ThisPlayer
ELSE
OUTPUT "No characters with this role are available"
ENDIF
ENDPROCEDURELoop that ends when a character is found or all 45 elements have been checked [1]
Test that the Player field is 0 (unassigned) inside the loop [1]
...AND the Role field matches ThisRole inside the loop [1]
If an available character is found, ThisPlayer is assigned to its Player field [1]
When found, a flag is set or the loop is ended [1]
Both OUTPUT messages placed logically (found and not found) [1]
Both OUTPUT statements correctly formed [1]
Open the file for writing, then for each of the 45 records join the four fields with '^' between them (turn the numbers into strings first) and write the line.
PROCEDURE Save()
DECLARE Index : INTEGER
DECLARE Line : STRING
OPENFILE "SaveFile.txt" FOR WRITE
FOR Index ← 1 TO 45
Line ← NUM_TO_STR(Character[Index].Player) & "^" & Character[Index].Role & "^" & Character[Index].Name & "^" & NUM_TO_STR(Character[Index].Level)
WRITEFILE "SaveFile.txt", Line
NEXT Index
CLOSEFILE "SaveFile.txt"
ENDPROCEDURELocal integer Index and string Line declared [1]
File SaveFile.txt opened in write mode and closed afterwards [1]
Loop through all 45 elements [1]
A line formed from all four fields inside the loop [1]
NUM_TO_STR() used on both Player and Level [1]
Three '^' separators correctly placed between the fields [1]
The line is written to the file inside the loop [1]
Text files hold only text, so the Boolean must be turned into text.
Encode Status as a character or string, for example "T" or "F" (or "TRUE"/"FALSE") [1]
Add the '^' separator and then this character/string to the end of the line [1]
Make the filename different each time.
Method: add a number (suffix) to the filename that goes up by one for each save [1]
Example: SaveFile01.txt then SaveFile02.txt [1]
▶ Whole paper
Video solution of the whole paper · by Papersdock. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.