1.1 Programming Part 1 Practice Paper
1.1 Programming Part 1 Practice Paper
Date: ________________________
Comments:
Page 1 of 210
Q1.
Stacks are also used to store a stack frame each time a subroutine call is made.
State two components of a stack frame.
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
(Total 2 marks)
Q2.
Figure 1 is a graph that shows the time it takes to travel between six locations in a
warehouse. The six locations have been labelled with the numbers 1 - 6. When there is no
edge between two nodes in the graph this means that it is not possible to travel directly
between those two locations. When there is an edge between two nodes in the graph the
edge is labelled with the time (in minutes) it takes to travel between the two locations
represented by the nodes.
(a) The graph is represented using an adjacency matrix, with the value 0 being used to
indicate that there is no edge between two nodes in the graph.
Complete the unshaded cells in Table 1 so that it shows the adjacency matrix for
Figure 1.
Table 1
1 2 3 4 5 6
Page 2 of 210
1
6
(2)
(b) Instead of using an adjacency matrix, an adjacency list could be used to represent
the graph. Explain the circumstances in which it would be more appropriate to use
an adjacency list instead of an adjacency matrix.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(c) State one reason why the graph shown in Figure 1 is not a tree.
___________________________________________________________________
___________________________________________________________________
(1)
(d) The graph in Figure 1 is a weighted graph. Explain what is meant by a weighted
graph.
___________________________________________________________________
___________________________________________________________________
(1)
Figure 2 contains pseudo-code for a version of Djikstra’s algorithm used with the graph in
Figure 1.
Q is a priority queue which stores nodes from the graph, maintained in an order based on
the values in array D. The reordering of Q is performed automatically when a value in D is
changed.
AM is the name given to the adjacency matrix for the graph represented in Figure 1.
Figure 2
Q ← empty queue
FOR C1 ← 1 TO 6
D[C1] ← 20
Page 3 of 210
P[C1] −1←
ADD C1 TO Q
ENDFOR
D[1] ← 0
WHILE Q NOT EMPTY
U ← get next node from Q
remove U from Q
FOR EACH V IN Q WHERE AM[U, V] > 0
A ←D[U] + AM[U, V]
IF A < D[V] THEN
D[V] ← A
P[V] ← U
ENDIF
ENDFOR
ENDWHILE
OUTPUT D[6]
(e) Complete the unshaded cells of Table 2 to show the result of tracing the algorithm
shown in Figure 2. Some of the trace, including the maintenance of Q, has already
been completed for you.
(7)
(f) What does the output from the algorithm in Figure 2 represent?
___________________________________________________________________
___________________________________________________________________
(1)
(g) The contents of the array P were changed by the algorithm. What is the purpose of
Page 4 of 210
the array P ?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(Total 16 marks)
Q3.
Write a program that checks which numbers from a series of numbers entered by the user
are prime numbers.
The program should get a number from the user and then display the messages:
The user should then be asked if they want to enter another number and the program
should repeat if they say that they do.
A prime number is a positive integer that will leave a remainder if it is divided by any
positive integer other than 1 and itself.
You may assume that each number entered by the user is an integer.
If your program only works correctly for some prime numbers you will get some marks for
this question. To get full marks for this question, your program must work correctly for any
valid integer value that the user enters.
(b) SCREEN CAPTURE(S) showing the result of testing the program by:
• entering the number 1
• then choosing to enter another number
• then entering the number 5
• then choosing to enter another number
• then entering the number 8
• and then choosing not to enter another number.
(1)
(Total 13 marks)
Q4.
WORDS WITH AQA
WORDS WITH AQA is a two-player game. Each player starts with 15 randomly-selected
tiles. Each tile represents a single letter; each letter has a points value as shown in Figure
Page 5 of 210
1. The tiles that a player has are called their "hand". Each player starts with a score of 50.
Figure 1
Players take turns to spell a two or more letter word using only the letter tiles in their hand.
Each tile may only be used once in the word. If on their turn they spell a valid word then
the tiles used in that word are removed from their hand and their score is increased. The
amount their score increases by depends on which tiles were used and the number of tiles
used in the word. Initially the score increases by the total points value of the tiles used. If a
valid word is spelt that uses more than seven tiles an additional 20 points are added to the
player’s score. If a valid word is spelt that uses six or seven tiles an additional five points
are added to the player’s score.
The player may then choose to either get three new tiles, get a number of new tiles equal
to the number of tiles used in the word they just spelt, get a number of new tiles equal to
three larger than the number of tiles used in the word they just spelt or to get no new tiles.
New tiles come from the tile queue.
If the word they spelt is not valid then their turn is over. No tiles are removed from their
hand and they get three tiles from the tile queue.
A valid word is one in which all the tiles needed to spell the word are in their hand and it is
a correctly-spelt English word.
The tile queue contains 20 randomly-selected tiles. The tiles in the queue are shown in
order, the tile at the front of the queue will be the next tile given to a player who gets a
new tile. When a tile is removed from the front of the queue and given to a player, a new
Page 6 of 210
randomly-selected tile is added to the rear of the queue. Players may look at the contents
of the tile queue at any time.
The game ends when either a player has used a total of more than 50 tiles in the valid
words they have spelt or when their hand contains 20 or more tiles. If Player One uses
more than 50 tiles first or has a hand with 20 or more tiles then Player Two gets to have
their turn before the game ends. At the end of the game each player’s score is reduced by
the points value of the letters on the tiles remaining in their hand. The winner is the player
with the highest score.
Figure 2
Figure 3
Player One goes first and spells the word DAT A. This is a valid word so Player
One’s score is increased by five points, 2 (D) + 1 (A) + 1 (T) + 1 (A), and the four
tiles used in that word are removed from the player’s hand. Player One chooses
to get a number of new tiles equal to three more than the number of tiles used in
the word they just spelt and so the first seven tiles in the tile queue are removed
from the queue and added to Player One’s hand. Seven random tiles are added
to the rear of the tile queue.
Player One’s hand before playing word with tiles being used highlighted:
Player One’s hand with tiles used removed and the seven tiles from the front of
the tile queue added to player’s hand:
Seven random letter tiles are added to the rear of the tile queue to replace those
removed:
Figure 4
It is now Player Two’s turn. Player Two spells the word AXONEMAL. This is a
valid word so Player Two’s score is increased by 34 points – 1 (A) + 5 (X) + 1
(O) + 1 (N) + 1 (E) + 2 (M) + 1 (A) + 2 (L) + 20 (word more than 7 letters long) –
to 84, and the eight tiles used in that word are removed from the player’s hand.
Player Two chooses not to get any new tiles.
Page 7 of 210
Player Two’s hand before playing word with tiles being used highlighted:
Figure 5
It is now Player One’s turn again. Player One spells the word NEED. This is not a
valid word as they have only got one E tile in their hand and the word they have spelt
needs two Es. Player One’s score is unchanged, no tiles are removed from Player
One’s hand and the first three tiles in the tile queue are removed from the queue and
added to Player One’s hand. Three random tiles are added to the rear of the tile
queue.
Player One has now got more than 20 tiles in their hand (21) so the game will end.
However, Player Two gets their turn before the game ends.
Figure 6
It is now Player Two’s turn. Player Two spells the word ZIC. This is not a valid
word as it is not an English word. Player Two’s score is unchanged, no tiles are
removed from Player Two’s hand and the first three tiles in the tile queue are
removed from the queue and added to Player Two’s hand. Three random tiles
are added to the rear of the tile queue.
Page 8 of 210
Tile queue at end of turn:
The game now stops and the final scores are calculated.
Figure 7
To calculate Player One’s final score the value of the tiles in their hand is subtracted from
their current score. Player One’s current score is 55. The value of the tiles in their hand is
43. So their final score is 55 – 43 = 12.
To calculate Player Two’s final score the value of the tiles in their hand is subtracted from
their current score. Player Two’s current score is 84. The value of the tiles in their hand is
18. So their final score is 84 – 18 = 66.
Player One has a final score of 12 and Player Two has a final score of 66 so Player Two
has won the game.
The first option is to play the game with the players having a random selection of letters in
their starting hands. The starting contents of the tile queue are random.
The second option is to play a training game in which the players have the same selection
of letters in their starting hands as shown in Figure 2. The starting contents of the tile
queue are random.
When playing the game each player takes it in turn to spell a word. When a player has
their turn they have five choices.
If they enter the string 1 then the point values of the 26 letters are displayed. The player’s
turn continues and they can choose any of the five options.
If they enter the string 4 then the current contents of the tile queue are displayed. The
player’s turn continues and they can choose any of the five options.
If they enter the string 7 then the current contents of their hand are displayed. The player’s
turn continues and they can choose any of the five options.
If they enter the string 0 then the player’s hand will be given enough tiles to take them
over the maximum number of tiles allowed in a hand. This will mean that the game will
finish (though if Player One chooses this option, Player Two will still have their turn before
the game finishes). The player’s turn then finishes.
If they enter any other string then this is treated as being an attempt at spelling a word
and the program checks to see if the word is valid. The player’s turn then finishes.
To check that a word is valid the program checks if the word is:
Page 9 of 210
• spelt using only letter tiles that are in the player’s hand
• in the list of allowed words. The allowed words are the words contained in the Data
File aqawords.txt.
Data File
A Data File named aqawords.txt is supplied with the Skeleton Program. This stores the
list of allowed English words that can be used in the game.
Q5.
(a) State the name of an identifier for a built-in function used in the Skeleton Program
that has a string parameter and returns an integer value.
___________________________________________________________________
___________________________________________________________________
(1)
(b) State the name of an identifier for a local variable in a method in the QueueOfTiles
class.
___________________________________________________________________
___________________________________________________________________
(1)
(c) The QueueOfTiles class implements a linear queue. A circular queue could have
been used instead.
Explain why a circular queue is often a better choice of data structure than a linear
queue.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(d) It could be argued that the algorithms for a linear queue lead to simpler program
code.
State one other reason why a linear queue is an appropriate choice in the Skeleton
Program even though circular queues are normally a better choice.
___________________________________________________________________
___________________________________________________________________
(1)
(e) State one additional attribute that must be added to the QueueOfTiles class if it
were to be implemented as a circular queue instead of as a linear queue.
___________________________________________________________________
Page 10 of 210
___________________________________________________________________
(1)
(f) Describe the changes that would need to be made to the Skeleton Program so that
the probability of a player getting a one point tile is the same as the probability of
them getting a tile worth more than one point. The changes you describe should not
result in any changes being made to the points value of any tile.
You should not change the Skeleton Program when answering this question.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(4)
(g) The GetChoice subroutine uses a built-in function to convert a string to uppercase.
You may assume that only lowercase characters are entered by the user.
You should not change the Skeleton Program when answering this question.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(4)
(Total 14 marks)
Q6.
Page 11 of 210
(a) This question refers to the subroutine CreateTileDictionary .
The points values for the letters J and X are to be changed so that they are not
worth as many points as the letters Z and Q.
Adapt the subroutine CreateTileDictionary so that the letters J and X are worth 4
points instead of 5 points.
Currently each player starts with 15 letter tiles. In the Main subroutine
StartHandSize is set to a value of 15.
Change the subroutine Main so that the user can choose what the value for
StartHandSize will be.
Before the main menu is displayed and before the first iteration structure in Main the
message “ Enter start hand size: ” should be displayed and the user's input
should be stored in StartHandSize. This should happen repeatedly until the user
enters a value for the start hand size that is between 1 and 20 inclusive.
(i) Your PROGRAM SOURCE CODE for the amended subroutine Main.
(4)
(ii) SCREEN CAPTURE(S) showing the requested test. You must make sure that
evidence for all parts of the requested test is provided in the SCREEN
CAPTURE(S).
(1)
When a player enters a word, a linear search algorithm is used to check to see if the
Page 12 of 210
word entered is in the list of AllowedWords. The subroutine CheckWordIsValid is to
be changed so that it uses a more time-efficient search algorithm.
You must write your own search routine and not use any built-in search function
that might be available in the programming language you are using.
Each item in AllowedWords that is compared to the word that the user entered
should be displayed on the screen.
Figure 1
BIG
BUG
FED
GET
JET
NOT
SIP
WON
Figure 2
1) If the user enters the word BIG then a value of True should be
returned and the words GET, BUG, BIG should be displayed, in that
order.
2) If the user enters the word JET then a value of True should be
returned and the words GET, NOT, JET should be displayed, in that
order.
3) If the user enters the word ZOO then a value of False should be
returned and the words GET, NOT, SIP, WON should be displayed, in
that order.
Page 13 of 210
After spelling a valid word the player decides which one of four options to select to
determine how many tiles will be added to their hand. Before choosing they can look
at the values of the tiles.
It would help the player make their decision if they were aware of how useful each
letter was by knowing the frequency with which each letter appears in the list of
allowed words.
The program is to be extended so that when the player chooses to view the tile
values they are also shown the number of times that each letter appears in the list of
allowed words.
Task 1
Create a new subroutine called CalculateFrequencies that looks through the list
of allowed words and displays each of the 26 letters in the alphabet along with the
number of times that the letter appears in the list of allowed words, which the
subroutine has calculated.
Task 2
Modify the DisplayTileValues subroutine so that after displaying the tile values it
also calls the CalculateFrequencies subroutine.
Task 3
Test that the changes you have made work:
(e) The scoring system for the game is to be changed so that if a player spells a valid
word they score points for all valid words that are a prefix of the word entered. A
prefix is the first x characters of a word, where x is a whole number between one
and the number of characters in the word.
In the Skeleton Program, AllowedWords contains the list of valid words that have
been read in from the Data File aqawords.txt.
Example
If the user enters the word TOO they will be awarded points for the valid words TOO
and TO as TO is a prefix of the word TOO. They will not be awarded points for the
word OO even though it is a valid word and is a substring of TOO because it is not a
prefix of TOO.
Page 14 of 210
Example
If the user enters the word BETTER they will be awarded points for the words
BETTER, BET and BE as these are all valid prefixes of the word entered by the
user. They would not be awarded points for BETT or BETTE as these are not valid
English words. They would not be awarded points for BEER as even though it is
contained in the word BETTER it is not a prefix.
Example
If the user enters the word BIOGASSES they will be awarded points for the words
BIOGASSES, BIOGAS, BIOG, BIO and BI as these are all valid prefixes of the word
entered by the user. They would not be awarded points for BIOGA, BIOGASS or
BIOGASSE as these are not valid English words. They would not be awarded points
for GAS as even though it is contained in the word BIOGASSES it is not a prefix.
Example
If the user enters the word CALMIEST they will not be awarded any points as even
though CALM at the start is a valid word the original word entered by the user,
CALMIEST, is not.
Example
If the user enters the word AN they will be awarded points for the word AN. They
would not be awarded points for A even though A at the start is a valid word as
points are only awarded for words that are at least two letters long.
Task 1
Write a recursive subroutine called GetScoreForWordAndPrefix that, if given a
valid word, returns the score of the word added to the score for any valid words that
are prefixes of the word.
To get full marks for this task the GetScoreForWordAndPrefix subroutine must
make use of recursion in an appropriate way to calculate the score for any prefixes
that are also valid words.
If your solution uses an alternative method to recursion you will be able to get most
but not all of the available marks for this question.
Task 2
Modify the UpdateAfterAllowedWord subroutine so that it calls the new
GetScoreForWordAndPrefix subroutine instead of the GetScoreForWord
subroutine.
Task 3
Test that the changes you have made to the program work:
Page 15 of 210
UpdateAfterAllowedWord and any other subroutines you have modified
when answering this question.
(11)
Q7.
Figure 1 shows the data Norbert, Phil, Judith, Mary, Caspar and Tahir entered into a
binary search tree.
Figure 1
Figure 2
FUNCTION TreeSearch(target, node)
OUTPUT ‘Visited ’, node
IF target = node THEN
RETURN True
ELSE IF target > node AND Exists(node, right) THEN
RETURN TreeSearch(target, node.right)
ELSE IF target < node AND Exists(node, left) THEN
RETURN TreeSearch(target, node.left)
ENDIF
RETURN False
ENDFUNCTION
The subroutine Exists takes two parameters – a node in the binary tree and a direction
(left or right). It returns a Boolean value indicating if the node given as a parameter
has a child node in the direction specified by the second parameter. For instance,
Exists(Mary, left) will return a value of False as there is no node to the left of Mary in
the binary tree.
node.right evaluates to the child node to the right of node, eg Judith.right is Mary.
node.left evaluates to the child node to the left of node, eg Judith.left is Caspar.
___________________________________________________________________
Page 16 of 210
___________________________________________________________________
(1)
(b) There are two base cases for the subroutine TreeSearch. State one of the base
cases.
___________________________________________________________________
___________________________________________________________________
(1)
(c) Complete the unshaded cells of the table below to show the result of tracing the
TreeSearch algorithm shown in Figure 2 with the function call
TreeSearch(Olivia, Norbert). You may not need to use all of the rows.
(3)
(Total 5 marks)
Q8.
(a) This question refers to the subroutine InputCoordinate in the Simulation class.
The warren and fox inspection options in the Skeleton Program do not currently
check if the coordinates entered by the user are on the landscape. This behaviour
needs to be improved so that an error message is displayed if the user inputs
coordinates for a location that is not on the landscape.
If the user runs a simulation with default settings then the landscape size is 15, so
valid locations have an x coordinate between 0 and 14, inclusive.
To achieve full marks for this question, the InputCoordinate subroutine should
work correctly for any landscape size, not just the default size of 15.
Test
Test your changes work by running the Skeleton Program and selecting the
following options:
Page 17 of 210
• “1. Run simulation with default settings”
• “3. Inspect fox”
Then input these three x coordinates for the location of the fox to inspect:
• −1
• 15
• 0
(b) The simulation is to be made more realistic by increasing the probability that a rabbit
will die as a result of other causes, such as disease or injury, as the rabbit ages.
Table 1 below summarises the probability of death by other causes for a rabbit of
each gender, up to the age of 5. The probabilities will continue to increase beyond
this age.
Table 1
0 0.05 0.05
1 0.08 0.05
2 0.11 0.1
3 0.17 0.15
4 0.25 0.2
5 0.38 0.25
Page 18 of 210
Create a new subroutine, CalculateNewAge, in the Rabbit class, that overrides the
CalculateNewAge subroutine in the Animal class.
The new CalculateNewAge subroutine in the Rabbit class should recalculate the
probability of death for a rabbit as the rabbit ages. The subroutine should also call
the subroutine that it has overridden in the Animal class to ensure that the standard
ageing process for a rabbit continues to be carried out as well.
Test
Check that the changes you have made work by conducting the following test:
• Select option “1. Run simulation with default settings” from the main menu.
• Then select option “2. Advance to next time period hiding detail” twice, to
advance the simulation to time period 2.
• Then select option “4. Inspect warren” and enter the x coordinate 1 and the y
coordinate 1.
• When asked “View individual rabbits (y/n)?” enter y.
(i) Your PROGRAM SOURCE CODE for the new subroutine CalculateNewAge
from the Rabbit class.
(5)
Your SCREEN CAPTURE(S) must clearly show the probability of death by other
causes of both a male and a female rabbit of age 2. SCREEN CAPTURE(S) do not
need to show the options that you have selected or the probability of death by other
causes for rabbits of other ages.
(1)
(c) The simulation is to be extended to represent the landscape that the animals live in.
Most of the landscape will be land, but two rivers will run through it. The locations of
the rivers are shaded in Figure 3.
Figure 3
Page 19 of 210
Each of the individual locations, eg (12, 7), within the landscape will be assigned to
be an area of either land or river.
Task 1
Modify the Location class so that it can store a representation of the type of terrain
at the location. This representation should be as a character, with “L” representing
land and “R” representing river.
Task 2
Modify the constructor subroutine of the Location class so that when a location is
created, the constructor is passed the type of terrain that the location will be and this
is stored appropriately.
Task 3
Modify the CreateLandscapeAndAnimals subroutine in the Simulation class so
that when the landscape is created the appropriate type of terrain, as shown in
Figure 3, is stored in each location. The terrain should be represented as a
character, with “L” representing land and “R” representing river.
Task 4
Modify the DrawLandscape subroutine in the Simulation class so that the correct
type of terrain at each location is displayed when the landscape is drawn.
Figure 4 shows one example of how the landscape could be drawn, with a letter “L”
indicating that a location contains land, and a letter “R” indicating that a location
contains part of a river. However, you are free to indicate the type of terrain at a
location in any way that you choose, so long as this is clear to the user.
Figure 4
Page 20 of 210
Task 5
Modify the CreateNewWarren and CreateNewFox subroutines in the Simulation
class so that warrens and foxes cannot be created in locations that are part of a
river.
Test
Check that the changes you have made in Tasks 1 to 4 (not Task 5) work by
conducting the following test:
• Select option “1. Run simulation with default settings” from the main menu.
(i) Your PROGRAM SOURCE CODE for the whole of the Location class,
including the constructor subroutine.
(3)
(iv) Your PROGRAM SOURCE CODE for the amended CreateNewWarren and
CreateNewFox subroutines from the Simulation class.
(3)
(v) SCREEN CAPTURE(S) for the described test, showing the correct type of
territory in each location on the landscape.
(1)
(d) The landscape affects the foxes’ ability to eat the rabbits. Foxes do not like to swim,
so will not cross the rivers on the landscape to eat. If a river lies between a fox and a
warren, the fox will not eat any rabbits in the warren, even if it is near enough for it to
do so.
As the rivers only run horizontally and vertically, and extend from one side of the
landscape to the other, a simple way to check if reaching a warren would require a
fox to cross a river is to:
Page 21 of 210
• Calculate the coordinates of all of the locations between the fox and the
warren in a horizontal line, level with the fox.
• Calculate the coordinates of all of the locations between the fox and the
warren in a vertical line, level with the fox.
• If any of the locations horizontally or vertically between the fox and the warren
contain a river, then the fox will not eat any of the rabbits in the warren as the
fox’s path to the warren crosses a river.
Figure 5 shows the locations that would need to be checked to see if fox F could eat
any rabbits in warren W. The locations that need to be checked are shown in black
and the rivers are shown in grey. As location (5, 7) contains part of a river, the fox
would not eat any rabbits in this warren.
Figure 5
If you have not been able to fully complete part (c), you will still be able to get most
of the marks for this question if you can correctly compute the coordinates of the
locations that would need to be checked to see if a river was present.
To get full marks for this question, your solution must work regardless of whether a
warren is above, below, to the left or to the right of a fox.
Task 1
Create a new subroutine CheckIfPathCrossesRiver, in the Simulation class, that
takes the coordinates of two locations in the landscape and checks if there is a river
between them.
Task 2
Modify the FoxesEatRabbitsInWarren subroutine in the Simulation class so that
it calls the CheckIfPathCrossesRiver subroutine, and ensures that if there is a
river between a fox and a warren then the fox will not eat any rabbits from the
Page 22 of 210
warren.
Test
Check that the changes you have made work by conducting the following test:
• Select option “1. Run simulation with default settings” from the main menu.
• Then select option “1. Advance to next time period showing detail”.
When the test is conducted, no rabbits in the warren at (1, 1) should be eaten as it is
bounded by rivers on all sides.
Your SCREEN CAPTURE(S) only needs to show what happens in the warren
at location (1, 1) when the simulation advances to the next time period. It
should contain similar information to Figure 6 below, but the exact number of
rabbits killed, dying of old age and other details may differ owing to the
random nature of parts of the simulation.
Figure 6
(1)
(Total 35 marks)
Q9.
In a particular programming language, the correct syntax for four different constructs is
defined by the syntax diagrams in Figure 1.
Figure 1
Page 23 of 210
In this language an example of a valid identifier is loopCount and an example of a valid
type is int.
(a) For each row in the table below, write Yes or No in the Valid? column to identify
whether or not the Example is a valid example of the listed Construct.
identifier Game_Over
(4)
A student has written Backus-Naur Form (BNF) production rules that are supposed to
define the same constructs as the syntax diagrams in Figure 1. Their BNF rules are
shown in Figure 2.
Figure 2
<procedure-def> ::= procedure <identifier> ( <paramlist> )
<paramlist> ::= <parameter> | <parameter> ; <paramlist>
<parameter> ::= <identlist> : <type> |
ref <identlist> : <type>
<identlist> ::= <identifier> | <identifier> , <identlist>
Page 24 of 210
<identifier> ::= <letter> | <letter> <identifier>
<type> ::= int | float | bool
(b) The BNF production rules in Figure 2 contain two errors. These errors mean that
the production rules do not represent the same statement types as the syntax
diagrams in Figure 1.
Error 1: ____________________________________________________________
___________________________________________________________________
___________________________________________________________________
Error 2: ____________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(1)
(Total 7 marks)
Q10.
A list data structure can be represented using a fixed-size array.
The pseudo-code algorithm in Figure 1 can be used to carry out one useful operation on
a list.
Figure 1
p ← 1
IF ListLength > 0 THEN
WHILE p <= ListLength AND List[p] < New
p ←p + 1
ENDWHILE
FOR q ← ListLength DOWNTO p DO
List[q + 1] ← List[q]
ENDFOR
Page 25 of 210
ENDIF
List[p] ← New
ListLength ← ListLength + 1
The DOWNTO command causes the loop counter value to decrease by one on each
iteration of the FOR loop.
The initial values of the variables for one particular execution of the algorithm are shown
in the trace table opposite, labelled Table 1. Array indexing starts at 1.
(a) Complete the trace table for the execution of the algorithm in Figure 1.
Table 1
List
ListLength New p q [1] [2] [3] [4] [5]
4 48 – – 19 43 68 107 –
(4)
___________________________________________________________________
___________________________________________________________________
(1)
(c) A list may be implemented using a static data structure such as a fixed-length array,
or using a dynamic data structure such as a linked list.
If the list were to be implemented using a dynamic data structure explain what the
heap would be used for.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(1)
(Total 6 marks)
Page 26 of 210
Q11.
A computer program is being developed to play a card game on a smartphone. The game
uses a standard deck of 52 playing cards, placed in a pile on top of each other.
The cards will be dealt (ie given out) to players from the top of the deck.
(a) Explain why a queue is a suitable data structure to represent the deck of cards in
this game.
___________________________________________________________________
___________________________________________________________________
(1)
(b) The queue representing the deck of cards will be implemented as a circular queue
in a fixed-size array named DeckQueue. The array DeckQueue has indices running
from 1 to 52.
The figure below shows the contents of the DeckQueue array and its associated
pointers at the start of a game. The variable QueueSize indicates how many cards
are currently represented in the queue.
(i) Twelve cards are dealt from the top of the deck.
What values are now stored in the FrontPointer and RearPointer pointers
and the QueueSize variable?
QueueSize = ___________
(1)
(ii) Next, a player gives up three cards and these are returned to the deck.
What values are now stored in the FrontPointer and RearPointer pointers
and the QueueSize variable?
Page 27 of 210
QueueSize = ___________
(1)
Your algorithm should output the value of the card that is to be dealt and make any
required modifications to the pointers and to the QueueSize variable.
It should also cope appropriately with any situation that might arise in the
DeckQueue array whilst a game is being played.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(6)
(Total 9 marks)
Q12.
A computer games programmer is writing a game. One aspect of the game involves a
character who can carry various items, such as a bag of seeds, and an axe, around with
her. The list of items that the character is currently carrying will be stored as a linked list of
items of the String data type. The list is stored in no particular order.
The game is being developed using object-oriented programming. The LinkedList class
will be used to store that list of items.
LinkedList
= Class
Public
Page 28 of 210
Procedure CreateList
Procedure DestroyList
Procedure AddItem(NewItem: String)
Procedure DeleteItem(DelItem: String)
Function ContainsItem(SearchItem: String): Boolean
Function IsEmpty: Boolean
Private
Start: Pointer
Current: Pointer
Previous: Pointer
End
(a) Creating a class such as the LinkedList class, that can be used by other parts of a
much bigger program, is a form of abstraction.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(1)
(b) Explain why the functions and procedures, such as AddItem have been declared to
be Public whilst the data items such as Start have been declared as Private.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
• Start is a pointer to the memory location of the first item in the linked list
• The variable DelItem, which will be passed to the DeleteItem operation as a
parameter, is a String that contains the name of the item to delete, exactly as
the name appears in the linked list
• The linked list is not empty, and does contain the item to be deleted
• For each item stored in the list, two fields are stored, which are called
DataValue and Next. The DataValue is the name of the item that is stored
and Next is a pointer to the memory location of the next item in the list. To
access the values stored in these fields at a particular memory location, such
as Current, the instructions Current. DataValue and Current. Next would
be used
• An operation called Release is provided by the operating system that will
make a specified memory location that is no longer required available for
re-use
• You should make use of the data items Current and Previous, both of which
are pointers, when searching the list to locate the item that is to be deleted.
Page 29 of 210
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(8)
(Total 11 marks)
Q13.
A dictionary is an abstract data type that allows pairs of values to be associated with each
other. For example, an English-French dictionary might associate English words with their
translations into French. In such a dictionary, "Apple" would be associated with "Pomme"
because "Pomme" is the French word for "Apple".
In each implementation, a record containing the English word and the equivalent French
word are stored at each index in the array that is in use.
The figure below shows how an English-French dictionary containing five words could be
implemented using these two methods.
Index English Word French Word Index English Word French Word
Page 30 of 210
[2] Lemon Citron [2] Lemon Citron
[6] [6]
[9] [9]
New words are inserted into the array in the The position to store a word is calculated
first available slot. The next word would be from the English word using a hashing
stored at position 6. function.
(a) Explain why, when the French translation of an English word needs to be looked up,
Implementation Two is more time efficient than Implementation One.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(b) In Implementation Two, it is possible that the hash function could compute the
same value for two different English words.
Explain what the effect of this would be, and how it could be dealt with.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(c) In Implementation Two, both the English and French words are stored at each
index in the Array. In this implementation, explain why it would not be possible to
perform reliable English to French translation if only the French words were stored.
___________________________________________________________________
Page 31 of 210
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(1)
(Total 5 marks)
Q14.
Figure 1 contains the pseudo-code for a program to output a sequence according to the
‘Fizz Buzz’ counting game.
Figure 1
OUTPUT "How far to count?"
INPUT HowFar
WHILE HowFar < 1
OUTPUT "Not a valid number, please try again."
INPUT HowFar
ENDWHILE
FOR MyLoop ← 1 TO HowFar
IF MyLoop MOD 3 = 0 AND MyLoop MOD 5 = 0
THEN
OUTPUT "FizzBuzz"
ELSE
IF MyLoop MOD 3 = 0
THEN
OUTPUT "Fizz"
ELSE
IF MyLoop MOD 5 = 0
THEN
OUTPUT "Buzz"
ELSE
OUTPUT MyLoop
ENDIF
ENDIF
ENDIF
ENDFOR
Test the program by showing the result of entering a value of 18 when prompted by the
program.
Test the program by showing the result of entering a value of -1 when prompted by the
program.
(b) SCREEN CAPTURE(S) for the tests conducted when a value of 18 is entered by
Page 32 of 210
the user and when a value of -1 is entered by the user.
(1)
(c) Explain why a FOR repetition structure was chosen instead of a WHILE repetition
structure.
___________________________________________________________________
___________________________________________________________________
(1)
(d) Even though a check has been performed to make sure that the variable HowFar is
greater than 1 there could be inputs that might cause the program to terminate
unexpectedly (crash).
Provide an example of an input that might cause the program to terminate and
describe a method that could be used to prevent this.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(3)
(e) Programs written in a high level language are easier to understand and maintain
than programs written in a low level language.
The use of meaningful identifier names is one way in which high level languages
can be made easier to understand.
State three other features of high level languages that can make high level
language programs easier to understand.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(3)
(f) The finite state machine (FSM) shown in Figure 2 recognises a language with an
alphabet of a and b.
Page 33 of 210
Figure 2
In the table below indicate whether each input string would be accepted or not
accepted by the FSM in Figure 2.
abbab
bbbbba
(2)
(g) In words, describe the language (set of strings) that would be accepted by this FSM
shown in Figure 2.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(Total 20 marks)
Q15.
State the name of an identifier for:
___________________________________________________________________
___________________________________________________________________
(1)
___________________________________________________________________
___________________________________________________________________
Page 34 of 210
(1)
___________________________________________________________________
___________________________________________________________________
(1)
___________________________________________________________________
___________________________________________________________________
(1)
Explain the need for a nested FOR loop and the role of the Count1 and Count2
variables.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(3)
Why has a named constant been used instead of the numeric value 5?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
Describe the purpose of the WHILE loop and the command within it in this
subroutine.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Page 35 of 210
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(3)
Describe why it is necessary to check if the monster moves into the same cell as the
flask and how any problem caused by this is solved by the Skeleton Program.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(3)
Explain why a WHILE loop has been made to complete the two moves for the
monster rather than a FOR loop.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(j) The subroutines in the Skeleton Program avoid the use of global variables: they
use local variables and parameter passing instead.
State two reasons why subroutines should, ideally, not use global variables.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(Total 19 marks)
Q16.
Based on the description in Statius' journal you are sure that this must be the right place.
Page 36 of 210
The blue-green moss covering the rocks and the dense tree foliage combine to conceal
the cave entrance; you almost walked straight past it and it was only through luck that you
saw it. There isn't any time to waste – ever since the journal was discovered, everyone
has been looking for this place. The thick cobwebs across the entrance prove that you
must be the first one here. You know that, if you are right, you could be the one that finds,
in the cavern below the mountain, the single draft of Styxian potion contained in Statius'
flask. The journal says that there is a fearsome beast lying in wait, but the risk is worth it.
Statius wrote that consuming the potion would grant the drinker invulnerability. Nothing
could hurt you, cut you, graze, scratch or bruise you. Your thoughts start to drift and you
imagine what you could do with such power.
"Snap out of it," you tell yourself. Someone else could find this place and you can't take
that risk; the flask contains only enough potion for one. Quickly you shoulder your pack,
then you light your torch, brush aside some cobwebs and step into the cave.
Inside, the ground is rough and you stumble several times. As you go deeper into the
mountain, the cave darkens and soon the only light is coming from your torch. After you
have been walking for a few minutes the cave widens and then ends abruptly. You take
out your copy of the journal. You read the description of the cave again. It says that, at the
end of the cave, there is a large fissure near the western part of the wall and that the
cavern, where the flask is hidden, is at the bottom of the fissure. You move over to the
west side of the cave. Sure enough, the fissure is there. You take off your pack and then
move carefully nearer the edge. The light from the torch does not reach far enough down
to reveal the bottom, but you can see that the fissure walls are too steep to get down
unaided so you will need your climbing equipment. You place your torch carefully on the
floor nearby and take your rope, pitons and carabiners out of your pack.
Your foot slips on some loose stones and you fall backwards into the fissure. You tumble
down the hole in a shower of dust and pebbles, falling into the cavern below. You land
painfully on the rocky floor.
It is dark; your torch is back in the cave and it weakly illuminates your immediate
surroundings but you cannot see any farther into the cavern. You become aware of a
sonorous noise around you and it takes you a few minutes to work out what it is. The
monster is asleep somewhere in the cavern and is snoring loudly. The sound reverberates
around you so you can't work out in which direction the monster lies.
You can see the bottom aperture of the fissure several metres above your head and try to
scramble up the wall to reach it, but the rock face is too sheer and you can't get sufficient
purchase. From what you can remember of the journal, you must be at the north-west
corner of the cavern.
You make your mind up. You can't get out of the cavern the way that you came in and the
monster could wake soon. You decide to explore the cavern. Maybe you will find another
way out. Maybe you will find the Styxian potion. You have no choice but to play the game
of...
MONSTER!
MONSTER!
The Skeleton Program in this Preliminary Material is a program for the one-player game
MONSTER!.
When playing MONSTER! the player starts in the north-west corner of a dark cavern. The
cavern is represented by a 7 × 5 rectangular grid of cells. The player's current position is
Page 37 of 210
indicated by an *. The player is presented with a list of five options: they can either return
to the main menu (where they can save the current game if they want to) or they can
move one cell in one of four possible directions. If they enter ‘N’ they will move one cell to
the north, ‘S’ will move them one cell to the south, ‘E’ will move them one cell to the east
and ‘W’ will move them one cell to the west. The initial position of a new game is shown in
Figure 1.
Figure 1
Figure 2 shows a new state, resulting from the user selecting ‘E’ in the starting position.
Figure 2
The aim of MONSTER! is to find the hidden treasure (a flask containing a Styxian potion)
that is in one of the cells of the cavern. Unfortunately, the cavern is dark and the only way
that a player can find the flask is to move around until they are in the same cell as the
flask. When a new game is started, the flask will be in a random position in the cavern
(though it won't be in the same cell as the player starts in). If the player moves into the cell
that contains the flask, then they win the game.
The cavern is also the lair of a fearsome monster that guards the flask. At the start of a
new game the monster is asleep. As the cavern is dark the player cannot see where the
monster is. If the player moves into the cell that contains the monster then the monster will
wake up and eat the player and the player will have lost the game.
The monster has set two traps in its cavern. The player cannot see where these traps are.
If the player moves into a cell that contains a trap then the monster will wake up. When
the monster is awake, it will move around the cavern until it either eats the player or the
player finds the flask. The monster is twice as fast as the player and makes two moves for
each player move. Each move is one cell in one of the four possible directions. When it is
awake the monster's skin glows so the player can see the position of the monster. The
monster can see in the dark and so knows where the player is. The current position of the
moving monster is indicated by an ‘M’ in the cavern displayed to the player.
Page 38 of 210
If the monster moves into the same cell as the flask, it kicks the flask out of the way and
the flask will be moved to the cell the monster came from. When the monster is awake, it
does not matter if the player (or the monster) moves into a cell containing one of the traps.
Figure 3 shows part of a possible game as displayed to the player. The player moves one
cell to the east, which triggers a trap that wakes the monster. The player is then shown
the position of the monster in the cavern. The monster then makes its first move and the
new state of the cavern is shown. It then makes its second move and the updated state of
the cavern is shown. It is then the player's turn to move.
Figure 3
Page 39 of 210
In the Skeleton Program there is a menu containing five options: ‘Start new game’, ‘Load
game’, ‘Save game’, ‘Play training game’ and ‘Quit’. If the user chooses ‘Load game’ then
the contents of a user-specified file are loaded and the user will start playing MONSTER!
from the game state saved in the file. If the user chooses ‘Save game’ then they will be
asked to enter a name for the file and then the current state of the game will be stored in a
file with the name supplied by the user. If the user chooses ‘Play training game’ then the
user will start playing MONSTER! from the game state shown in Figure 4.
Figure 4
‘F’ denotes the position of the flask; ‘T’ denotes the position of a trap. The flask, traps and
monster are not displayed to the player when the training game starts.
Q17.
(a) This question refers to the subroutines CheckValidMove and PlayGame.
The Skeleton Program currently does not make all the checks needed to ensure
that the move entered by a player is an allowed move. It should not be possible to
Page 40 of 210
make a move that takes a player outside the 7×5 cavern grid.
(ii) Your amended PROGRAM SOURCE CODE for the subroutine PlayGame.
(1)
(iii) SCREEN CAPTURE(S) for a test run showing a player trying to move north
when they are at the northern end of the cavern.
(1)
(b) This question refers to the PlayGame subroutine and will extend the functionality of
the game.
The final score will be displayed to the user at the end of the game. At the end of the
game, either the player will have found the flask or the player will have been eaten
by the monster.
The final score should be displayed with the message "Your score was: Y " where Y
is the value of Score.
Task 1
Adapt the Skeleton Program so that the scoring system described above is
implemented, with the value of Score being updated as indicated and the required
message being displayed at the end of a game.
Task 2
Test that the changes you have made work by conducting the following test:
Page 41 of 210
• move east.
(i) Your amended PROGRAM SOURCE CODE for the subroutine PlayGame and
(if relevant) the PROGRAM SOURCE CODE for any other subroutine(s) you
have amended.
(8)
The player will now have access to a close-range trap detector. After making a
directional move in the cavern, the trap detector will perform a sweep of the
neighbouring cells and report back if a trap is detected. Unfortunately, the detector
can only detect the presence of a trap in a neighbouring cell, and not which
individual cell the trap is in.
In Figure 1 the shaded cells show the cells that would be scanned by the trap
detector if the player were in the cell marked P1 or P2. The trap detector cannot
scan outside the cavern.
Figure 1
Task 1
Create a new subroutine, TrapDetector, that, when given the current location of
the player, returns True if a trap is in a neighbouring cell and False if there is no
trap in a neighbouring cell.
When creating this subroutine you should ensure that your solution is efficiently
coded.
Task 2
Modify the PlayGame subroutine so that after the player moves and the new state of
the cavern is displayed:
• the message ‘Trap detected’ is displayed if there is a trap in any
neighbouring cell.
• the message ‘No trap detected’ is displayed if there are no traps in any
neighbouring cell.
Task 3
Test that your program works by loading the training game and showing that:
• a trap is detected after the player’s first move, west
Page 42 of 210
• a trap is detected after the player’s second move, south
• a trap is not detected after the player’s third move, west.
(ii) Your amended PROGRAM SOURCE CODE for the subroutine PlayGame.
(1)
(iii) SCREEN CAPTURE(S) showing the required sequence of tests being carried
out, with the trap detected message being displayed after each of the first two
moves and the trap not detected message being displayed after the third
move.
(1)
Figure 2
In your answer you should ensure that you discuss changes to the data held in
the Cavern variable and how the subroutines ResetCavern and
CheckValidMove will need to be altered.
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
Page 43 of 210
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
(5)
(v) A request has been made that the layout of the whole cavern should be more
random. It has been suggested that all of the cells should be made a random
choice between rock and normal space during setup.
Identify two problems that might occur with the MONSTER! game if this
suggestion was made to the program.
______________________________________________________________
______________________________________________________________
______________________________________________________________
______________________________________________________________
(2)
(Total 35 marks)
Q18.
ℝ denotes the set of real numbers, which includes the natural numbers, the rational
numbers and the irrational numbers.
___________________________________________________________________
(1)
___________________________________________________________________
(1)
(Total 2 marks)
Q19.
(a) What is the decimal equivalent of the hexadecimal number D6 16? Show your
working.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
Page 44 of 210
(b) Represent the decimal value 9.37510 as an unsigned binary fixed point number, with
4 bits before and 4 bits after the binary point.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(c) Represent the decimal value -6710 as an 8-bit two’s complement binary integer.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
010010002
011000112 +
Answer:
(1)
(e) What problem has resulted from performing the calculation using 8-bit two’s
complement binary?
___________________________________________________________________
___________________________________________________________________
(1)
(Total 8 marks)
Q20.
(a) Complete the table below and draw the symbol for an AND gate in the box.
Page 45 of 210
(2)
(b) Using the laws of Boolean algebra, simplify the following Boolean expression.
A.B. (A + B)
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Answer ___________________________
(3)
(c) Using the laws of Boolean algebra, simplify the following Boolean expression.
(X + Y).(X + )
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Answer ___________________________
(3)
(Total 8 marks)
Q21.
The famous detective John Stout was called in to solve a perplexing murder mystery. He
determined the following facts.
Page 46 of 210
the dining room when the murder was committed.
f If Martin was in the dining room at the time the murder was committed, then
Paul killed Nathan.
g If Kevin was in the hall at the time of the murder, then Suzanne killed Nathan
by a blow to the neck with a saucepan.
A Paul
B Steve
C Suzanne
D Ian
E It is not possible for John Stout to solve the crime.
(1)
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(Total 3 marks)
Q22.
A finite state machine (FSM) can be used to define a language: a string is allowed in a
language if it is accepted by the FSM that represents the rules of the language.
Figure 1 shows the state transition diagram for an FSM.
Figure 1
Page 47 of 210
An FSM can be represented as a state transition diagram or as a state transition table.
The table below is an incomplete state transition table for Figure 1 .
S3
S3
(1)
(b) Any language that can be defined using an FSM can also be defined using a
regular expression.
The FSM in Figure 1 defines the language that allows all strings containing at least,
either two consecutive 1s or two consecutive 0s.
The strings 0110, 00 and 01011 are all accepted by the FSM and so are valid
strings in the language.
The strings 1010 and 01 are not accepted by the FSM and so are not valid strings in
the language.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(3)
(c) Backus-Naur Form (BNF) can be used to define the rules of a language.
Page 48 of 210
Figure 2
Rule
number
1 <fullname> ::= <title>_<name>_<endtitle> |
<name> |
<title>_<name> |
<name>_<endtitle>
2 <title> ::= MRS | MS | MISS | MR | DR | SIR
3 <endtitle> ::= ESQUIRE | OBE | CBE
<name> ::= <word> |
4
<name>_<word>
5 <word> ::= <char><word>
6 <char> ::= A | B | C | D | E | F | G | H | I |
J | K | L | M | N | O | P | Q | R |
S | T | U | V | W | X | Y | Z
BNF can be used to define languages that are not possible to define using regular
expressions. The language defined in Figure 2 could not have been defined using
regular expressions.
Complete the table below by writing either a ‘Y’ for Yes or ‘N’ for No in each row.
(1)
(d) There is an error in rule 5 in Figure 2 which means that no names are defined by
the language.
Explain what is wrong with the production rule and rewrite the production rule so that
the language does define some names – the names ‘BEN D JONES’, ‘JO
GOLOMBEK’ and ‘ALULIM’ should all be defined.
___________________________________________________________________
___________________________________________________________________
Page 49 of 210
___________________________________________________________________
___________________________________________________________________
(2)
(Total 7 marks)
Q23.
Create a folder / directory for your new program.
One method for converting a decimal number into binary is to repeatedly divide by 2 using
integer division. After each division is completed, the remainder is output and the integer
result of the division is used as the input to the next iteration of the division process. The
process repeats until the result of the division is 0.
Outputting the remainders in the sequence that they are calculated produces the binary
digits of the equivalent binary number, but in reverse order.
For example, the decimal number 210 could be converted into binary as shown below.
Task 1
Write a program that will perform the conversion process described above. The program
should display a suitable prompt asking the user to input a decimal number to convert and
then output the bits of the binary equivalent of the decimal number in reverse order.
Task 2
Improve the program so that the bits are output in the correct order, e.g. for 210 the output
would be 11010010.
Task 3
Test the program works by entering the value 210.
(a) Your PROGRAM SOURCE CODE after you have completed both Task 1 and Task
2.
If you complete Task 1 but do not attempt Task 2 then a maximum of 9 marks will
be awarded.
(12)
Page 50 of 210
(b) SCREEN CAPTURE(S) for the test showing the output of the program when 210 is
entered.
The marks for this test will be awarded whether the binary digits are output in
reverse order or in the correct order.
(2)
(Total 14 marks)
Q24.
Based on the description in Statius' journal you are sure that this must be the right place.
The blue-green moss covering the rocks and the dense tree foliage combine to conceal
the cave entrance; you almost walked straight past it and it was only through luck that you
saw it. There isn't any time to waste – ever since the journal was discovered, everyone
has been looking for this place. The thick cobwebs across the entrance prove that you
must be the first one here. You know that, if you are right, you could be the one that finds,
in the cavern below the mountain, the single draft of Styxian potion contained in Statius'
flask. The journal says that there is a fearsome beast lying in wait, but the risk is worth it.
Statius wrote that consuming the potion would grant the drinker invulnerability. Nothing
could hurt you, cut you, graze, scratch or bruise you. Your thoughts start to drift and you
imagine what you could do with such power.
"Snap out of it," you tell yourself. Someone else could find this place and you can't take
that risk; the flask contains only enough potion for one. Quickly you shoulder your pack,
then you light your torch, brush aside some cobwebs and step into the cave.
Inside, the ground is rough and you stumble several times. As you go deeper into the
mountain, the cave darkens and soon the only light is coming from your torch. After you
have been walking for a few minutes the cave widens and then ends abruptly. You take
out your copy of the journal. You read the description of the cave again. It says that, at the
end of the cave, there is a large fissure near the western part of the wall and that the
cavern, where the flask is hidden, is at the bottom of the fissure. You move over to the
west side of the cave. Sure enough, the fissure is there. You take off your pack and then
move carefully nearer the edge. The light from the torch does not reach far enough down
to reveal the bottom, but you can see that the fissure walls are too steep to get down
unaided so you will need your climbing equipment. You place your torch carefully on the
floor nearby and take your rope, pitons and carabiners out of your pack.
Your foot slips on some loose stones and you fall backwards into the fissure. You tumble
down the hole in a shower of dust and pebbles, falling into the cavern below. You land
painfully on the rocky floor.
It is dark; your torch is back in the cave and it weakly illuminates your immediate
surroundings but you cannot see any farther into the cavern. You become aware of a
sonorous noise around you and it takes you a few minutes to work out what it is. The
monster is asleep somewhere in the cavern and is snoring loudly. The sound reverberates
around you so you can't work out in which direction the monster lies.
You can see the bottom aperture of the fissure several metres above your head and try to
scramble up the wall to reach it, but the rock face is too sheer and you can't get sufficient
purchase. From what you can remember of the journal, you must be at the north-west
corner of the cavern.
You make your mind up. You can't get out of the cavern the way that you came in and the
monster could wake soon. You decide to explore the cavern. Maybe you will find another
way out. Maybe you will find the Styxian potion. You have no choice but to play the game
of...
Page 51 of 210
MONSTER!
MONSTER!
The Skeleton Program in this Preliminary Material is a program for the one-player game
MONSTER!.
When playing MONSTER! the player starts in the north-west corner of a dark cavern. The
cavern is represented by a 7 × 5 rectangular grid of cells. The player's current position is
indicated by an *. The player is presented with a list of five options: they can either return
to the main menu (where they can save the current game if they want to) or they can
move one cell in one of four possible directions. If they enter ‘N’ they will move one cell to
the north, ‘S’ will move them one cell to the south, ‘W’ will move them one cell to the west
and ‘E’ will move them one cell to the east. The initial position of a new game is shown in
Figure 1.
Figure 1
Figure 2 shows a new state, resulting from the user selecting ‘E’ in the starting position.
Figure 2
The aim of MONSTER! is to find the hidden treasure (a flask containing a Styxian potion)
that is in one of the cells of the cavern. Unfortunately, the cavern is dark and the only way
that a player can find the flask is to move around until they are in the same cell as the
flask. When a new game is started, the flask will be in a random position in the cavern
(though it won't be in the same cell as the player starts in). If the player moves into the cell
that contains the flask, then they win the game.
The cavern is also the lair of a fearsome monster that guards the flask. At the start of a
new game the monster is asleep. As the cavern is dark the player cannot see where the
Page 52 of 210
monster is. If the player moves into the cell that contains the monster then the monster will
wake up and eat the player and the player will have lost the game.
The monster has set two traps in its cavern. The player cannot see where these traps are.
If the player moves into a cell that contains a trap then the monster will wake up. When
the monster is awake, it will move around the cavern until it either eats the player or the
player finds the flask. The monster is twice as fast as the player and makes two moves for
each player move. Each move is one cell in one of the four possible directions. When it is
awake the monster's skin glows so the player can see the position of the monster. The
monster can see in the dark and so knows where the player is. The current position of the
moving monster is indicated by an ‘M’ in the cavern displayed to the player.
If the monster moves into the same cell as the flask, it kicks the flask out of the way and
the flask will be moved to the cell the monster came from. When the monster is awake, it
does not matter if the player (or the monster) moves into a cell containing one of the traps.
Figure 3 shows part of a possible game as displayed to the player. The player moves one
cell to the east, which triggers a trap that wakes the monster. The player is then shown
the position of the monster in the cavern. The monster then makes its first move and the
new state of the cavern is shown. It then makes its second move and the updated state of
the cavern is shown. It is then the player's turn to move.
Figure 3
Page 53 of 210
In the Skeleton Program there is a menu containing three options: ‘Start new game’, ‘Play
training game’ and ‘Quit’. If the user chooses ‘Play training game’ the user will start
playing MONSTER! from the game state shown in Figure 4.
Figure 4
Page 54 of 210
'F' denotes the position of the flask; 'T' denotes the position of a trap. The flask, traps and
monster are not displayed to the player when the training game starts.
Q25.
(a) This question refers to the subroutines CheckValidMove and Play in the Game
class.
The Skeleton Program currently does not make all the checks needed to ensure
that the move entered by a player is an allowed move. It should not be possible to
make a move that takes a player outside the 7 × 5 cavern grid.
The subroutine Play needs to be adapted so that it displays an error message to the
user if an illegal move is entered. The message should state "That is not a valid
move, please try again".
(ii) Your amended PROGRAM SOURCE CODE for the subroutine Play.
(2)
(iii) SCREEN CAPTURE(S) for a test run showing a player trying to move west
when they are at the western end of the cave.
(1)
The game is to be altered so that there is a new type of enemy: a sleepy enemy. A
sleepy enemy is exactly the same as a normal enemy, except that after making four
moves it falls asleep again.
Task 1
Create a new class called SleepyEnemy that inherits from the Enemy class.
Task 2
Create a new integer attribute in the SleepyEnemy class called MovesTillSleep.
Task 3
Create a new public subroutine in the SleepyEnemy class called
ChangeSleepStatus. This subroutine should override the ChangeSleepStatus
subroutine from the Enemy class. The value of MovesTillSleep should be set to 4
in this subroutine.
Task 4
Create a new public subroutine in the SleepyEnemy class called MakeMove. This
Page 55 of 210
subroutine should override the MakeMove subroutine from the Enemy class. When
called this subroutine should reduce the value of MovesTillSleep by 1 and then
send the monster to sleep if MovesTillSleep has become equal to 0.
Task 5
Modify the Game class so that the Monster object is of type SleepyEnemy (instead of
Enemy) .
Task 6
Check that the changes you have made work by conducting the following test:
(i) Your PROGRAM SOURCE CODE for the new SleepyEnemy class.
(8)
(c) This question refers to the Game and Character classes and will extend the
functionality of the game.
The game should be altered so that once per game the player can shoot an arrow
instead of making a move in the cavern. The arrow travels in a straight line, in a
direction of the player's choice, from the cell the player is in to the edge of the
cavern. If the arrow hits the monster then the player wins the game and a message
saying that they have shot the monster should be displayed.
For this question you are only required to extend the program so that it checks if the
monster is hit by the arrow when the user chooses to shoot an arrow northwards.
However, the user should be able to select any of the four possible directions.
In the diagram below, the two shaded cells show the cells which, if the monster is in
one of them, would result in the player winning the game, as long as the player is in
the cell five to the east and three to the south and chooses to shoot an arrow
northwards.
Task 1
Modify the DisplayMoveOptions subroutine in the Game class so that the option to
enter A to shoot an arrow is added to the menu.
Page 56 of 210
Task 2
Create a new Boolean attribute called HasArrow in the Character class.
The value of HasArrow should be set to True when a new object of class Character
is instantiated.
Task 3
Create a new public subroutine called GetHasArrow in the Character class that
returns the value of the HasArrow attribute to the calling routine.
Task 4
Modify the CheckValidMove subroutine in the Game class so that:
Task 5
Create a new public subroutine called GetArrowDirection in the Character class.
The user should be asked in which direction they would like to shoot an arrow (N, S,
E or W) and the value entered by the user should be returned to the calling routine.
If an invalid direction is entered then the user should be repeatedly asked to enter a
new direction, until a valid direction is entered.
Task 6
Modify the Play subroutine in the Game class so that if the move chosen by the user
is not M it then checks if the move chosen is A.
If the move chosen was A, then there should be a call to the player's
GetArrowDirection subroutine. If the user chooses a direction of N then the
program should check to see if the monster is in one of the squares directly north of
the player's current position. If it is then a message saying "You have shot the
monster and it cannot stop you finding the flask" should be displayed. The
value of FlaskFound should then be set to TRUE.
After the arrow has been shot, if the monster is still alive and awake, it is now the
monster's turn to move, the player should remain in the same cell as they were in
before the arrow was shot.
There is no need to write any code that checks if the monster has been shot when
the player chooses to shoot either to the east, to the west or to the south.
Task 7: test 1
Test that the changes you have made work by conducting the following test:
Task 8: test 2
Test that the changes you have made work by conducting the following test:
Page 57 of 210
• play the training game
• move east
• shoot an arrow
• choose a direction of N for the arrow
• shoot an arrow.
(iii) Your amended PROGRAM SOURCE CODE for the class Character.
(8)
(iv) Your amended PROGRAM SOURCE CODE for the subroutine Play.
(6)
Q26.
A particular computer uses a normalised floating point representation with an 8-bit
mantissa and a 4-bit exponent, both stored using two’s complement.
Four bit patterns that are stored in this computer’s memory are listed in the figure below
and are labelled A, B, C, D. Three of the bit patterns are valid floating point numbers and
one is not.
Page 58 of 210
(a) Complete the table below. In the Correct letter (A-D) column shade the appropriate
lozenge A, B, C or D to indicate which bit pattern from above is an example of the
type of value described in the Value description column.
(3)
Mantissa Exponent
Calculate the decimal equivalent of the number. Show how you have arrived at your
answer.
Page 59 of 210
___________________________________________________________________
___________________________________________________________________
Answer ___________________________
(2)
(c) Write the normalised floating point representation of the negative decimal value
-6.75 in the boxes below. Show how you have arrived at your answer.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Answer:
Mantissa Exponent
(3)
Mantissa Exponent
Mantissa Exponent
Explain the effects of using the proposed alternative representation instead of the
existing representation.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Page 60 of 210
(2)
(Total 10 marks)
Q27.
(a) The table below lists six Boolean equations. Three of them are correct, the others
are not. Shade the lozenges next to the three equations that are correct.
A⋅ =1
A+ B=
A+ 1= 1
A ⋅( A + B ) = A
A + ( A ⋅B ) = B
A ⋅1 = 1
(3)
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Answer ___________________________
(3)
(Total 6 marks)
Q28.
Create a folder / directory in this question for your new program.
The algorithm, represented using pseudo-code below, and the variable table, describe a
program that calculates and displays all of the prime numbers between 2 and 50,
inclusive.
The MOD operator calculates the remainder resulting from an integer division
eg 10 MOD 3 = 1.
If you are unsure how to use the MOD operator in the programming language you are
Page 61 of 210
using, there are examples of it being used in the Skeleton Program.
(b) SCREEN CAPTURE(S) for the test showing the correct working of the program.
(1)
(c) Describe the changes that would need to be made to the algorithm shown above,
so that instead of displaying the prime numbers between 2 and 50, inclusive, it
displays all the prime numbers between 2 and a value input by the user, inclusive.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Page 62 of 210
___________________________________________________________________
(3)
(Total 15 marks)
Q29.
State the name of an identifier for:
___________________________________________________________________
___________________________________________________________________
(1)
___________________________________________________________________
___________________________________________________________________
(1)
___________________________________________________________________
___________________________________________________________________
(1)
Describe how this subroutine could be rewritten so that instead of there being three
lines of code that change the value in the start square, there could be just one line of
code that does this. The functionality of the MakeMove subroutine should not be
altered by the changes you describe.
___________________________________________________________________
___________________________________________________________________
(1)
(e) Look at the last selection structure in the MAIN PROGRAM BLOCK.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(f) The logic of a selection structure can be represented using a decision table.
The table shows an attempt to represent the logic of this selection structure.
Page 63 of 210
>= 97
Conditions Y N Y Y
<= 123
N Y N Y
Change value of PlayAgain
Action X X X
Explain why this decision table is not an accurate representation of the logic of this
selection structure.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(3)
(Total 9 marks)
Q30.
(a) This question refers to the MAIN PROGRAM BLOCK and will extend the
functionality of the Skeleton Program.
The number of moves made by the players in a game of CAPTURE THE SARRUM
will be tracked. A variable called NoOfMoves will be used to store the number of
moves completed by the players. At the start of every game NoOfMoves should be
set to an initial value of zero.
Each time a player enters a legal move 1 should be added to the value stored in
NoOfMoves.
After the call to the MakeMove subroutine, the NoOfMoves variable should be updated
and then a message should be displayed saying "The number of moves completed
so far: n" − where n is the value of NoOfMoves.
(i) Your PROGRAM SOURCE CODE for the amended MAIN PROGRAM
BLOCK.
(4)
Page 64 of 210
(2)
When the user has entered the start square and the finish square for their move, a
number of checks are made to see if their intended move is legal.
(ii) SCREEN CAPTURE(S) showing the requested test. You must make sure that
evidence for all parts of the requested test by the user is provided in the
SCREEN CAPTURE(S).
(3)
A kashshaptu moves in the same way as a sarrum (one square in any direction).
Like all the other pieces, a kashshaptu cannot move into a square containing a
piece of the same colour and when a kashshaptu is moved into a square containing
the opponent’s sarrum, it captures the sarrum and the game is over.
When a move would cause the kashshaptu to enter a square containing one of the
opponent’s pieces (except the sarrum), the kashshaptu stays in its start square and
the opponent’s piece changes colour and now belongs to the player who played the
kashshaptu. It then becomes the other player's turn.
Figure 1
Page 65 of 210
White enters a start square of 23 and a finish square of 22. The board should now
look like this:
Figure 2
Page 66 of 210
White enters a start square of 23 and a finish square of 22. The board should now
look like this:
Task 1
Adapt the program source code for the CheckMoveIsLegal subroutine, so that a
kashshaptu (represented by the letter K) has the same legal moves as a sarrum.
Task 2
Adapt the program source code for the MakeMove subroutine, so that when a redum
is promoted, it becomes a kashshaptu (represented by the symbol K) and so that a
kashshaptu moves and captures in the way described.
You need to adapt only the program source code so that the player with the White
Page 67 of 210
pieces can promote a redum to a kashshaptu and move a kashshaptu.
Task 3
Test that the changes you have made work:
(ii) Your PROGRAM SOURCE CODE for the amended subroutine MakeMove.
(5)
(d) This question will further extend the functionality of the Skeleton Program.
You can attempt this question regardless of whether or not you produced a solution
to Question (c) that correctly added the kashshaptu piece to the game.
FEN can be adapted to represent game positions from chess variants like
CAPTURE THE SARRUM.
FEN defines a particular game position in one line of text using ASCII characters.
This line of text can then be saved into a file or copied for use in another program.
To represent a game position in CAPTURE THE SARRUM, the FEN needs to
represent two items of information about the game position – the board state (what
pieces are on what squares) and which player’s turn it is.
The first item in a FEN record for CAPTURE THE SARRUM is the board state. The
board state is represented rank by rank – starting with rank 1 and ending with rank
8. Within each rank the contents of each square are described – starting with file 1
and ending with file 8.
After the board state, there will be either a W or B character to indicate if it is White’s
or Black’s turn.
Figure 3 shows an example board position from a game and the equivalent FEN
Page 68 of 210
record.
Figure 4 shows the initial board position and the equivalent FEN record.
Figure 3
Figure 4
Task 1
Create a new subroutine, GenerateFEN, which takes two parameters (the board and
whose turn it is) and creates a string containing the FEN record for the current state
of a CAPTURE THE SARRUM game. It should return this string to the calling
routine. You may choose whether to make the new subroutine a function or a
procedure.
Page 69 of 210
You are likely to get some marks for this task, even if your subroutine is only
partially working.
It does not matter if your new subroutine will work correctly for positions containing a
kashshaptu (from Question (c)).
(i) Your PROGRAM SOURCE CODE for the new subroutine GenerateFEN.
(13)
Task 2
Adapt the MAIN PROGRAM BLOCK so that the FEN record returned by the
GenerateFEN subroutine is displayed before asking the player to enter their move.
Task 3
Test that the changes you have made work:
(ii) Your PROGRAM SOURCE CODE for the amended MAIN PROGRAM
BLOCK.
(3)
Q31.
A computer program is being developed that will simulate the organisation of wagons
(trucks) in a railway shunting yard. The simulation will be based on a model developed by
the shunting yard manager and a systems analyst.
___________________________________________________________________
___________________________________________________________________
(1)
The diagram below shows the layout of the railway yard. The wagons enter the yard and
are pushed into an appropriate siding, depending upon their final destination. Each siding
can hold many wagons. Wagons can only enter and leave a siding using the Yard
Entrance / Exit at the west.
Page 70 of 210
Wagons will be represented as objects in an object-oriented programming language.
(b) Explain why a stack data structure is appropriate for representing a siding.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(c) The computer program developer intends to implement a stack by using a fixed
length array of 30 wagon objects, named StackArray, with indices running from 1 to
30. An integer variable TopOfStackPointer, that will store the array index of the
item at the top of the stack, will also be used. The first object stored in the array will
be stored at index 1, the second at index 2 and so on. TopOfStackPointer will be
initialised to 0.
Write a pseudo-code algorithm for the Pop operation to remove a value from the
stack and store it in a wagon object variable named CurrentWagon.
Your algorithm should cope appropriately with any potential errors that might occur.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(4)
Page 71 of 210
(d) Wagons come in two different categories: open wagons (without a roof) and closed
wagons (with a roof). Closed wagons can be either refrigerated or non-refrigerated.
(3)
(e) The Wagon class has data fields OwnerName, Weight and NumberOfWheels.
Wagon = Class
Public
Procedure CreateWagon
Function GetOwnerName
Function GetWeight
Function GetNumberOfWheels
Private
OwnerName: String
Weight: Real
NumberOfWheels: Integer
End
You should include the necessary data fields and any additional procedures or
functions that the class would require in your definition.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Page 72 of 210
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(4)
(Total 14 marks)
Q32.
The Backus-Naur Form (BNF) production rules below define the syntax of a number of
programming language constructs.
(a) The table below contains a list of variable names. Place a tick in each row if the
stated variable name is a valid <variable> for the production rules above.
Valid?
<variable> ( any
number of
rows)
a
money_paid
taxrate2
2ndPlayerName
(1)
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Page 73 of 210
(1)
(c) Here is an example of a valid <forloop> :
FOR count = 1 TO 10
The BNF production rules above can be used to check whether or not a <forloop>
is syntactically correct.
Describe one example of why a syntactically correct <forloop> may still produce
an error when a program is compiled.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(1)
(Total 3 marks)
Q33.
The image below shows an 8-bit bit pattern.
1 0 1 1 0 1 1 0
(a) If the bit pattern above is an unsigned binary integer, what is the denary
equivalent of this bit pattern?
___________________________________________________________________
___________________________________________________________________
(1)
(b) If the bit pattern above is a two’s complement binary integer, what is the denary
equivalent of this bit pattern?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(c) What is the range of denary numbers that can be represented using 8-bit two’s
complement binary integers?
___________________________________________________________________
___________________________________________________________________
Page 74 of 210
___________________________________________________________________
___________________________________________________________________
(2)
(d) If the bit pattern above is an unsigned binary fixed point number with 3 bits
before and 5 bits after the binary point, what is the denary equivalent of this bit
pattern?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(f) Why are bit patterns often displayed using hexadecimal instead of binary?
___________________________________________________________________
___________________________________________________________________
(1)
(g) Describe a method that can, without the use of binary addition, multiply any
unsigned binary integer by the binary number 10 (the denary number 2).
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(Total 12 marks)
Q34.
A pseudo-code representation of an algorithm is given below.
FOR x ←0 TO 7 DO
IF (x MOD 16 >= 4) AND (x MOD 16 <= 11)
THEN c ← 1
Page 75 of 210
ELSE c ←0
ENDIF
IF (x MOD 8 >= 2) AND (x MOD 8 <= 5)
THEN b ← 1
ELSE b ←0
ENDIF
IF (x MOD 4 = 0) OR (x MOD 4 = 3)
THEN a ← 0
ELSE a ←
1
ENDIF
OUTPUT (c, b, a)
ENDFOR
The MOD operator calculates the remainder resulting from an integer division. For example,
7 MOD 5 = 2, 14 MOD 5 = 4.
The statement OUTPUT (c, b, a) will display the contents of the variable c, followed by
the contents of the variable b and then the contents of the variable a.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
(2)
(b) The decision table shown in Table 1 represents the logic of the second selection
structure in the algorithm above. The decision table is only partially complete; the
shaded cells that should show the actions to be taken have not been filled in.
Table 1
Action b ←1
b ←0
Complete Table 1 so that it shows the actions to be taken when the conditions have
particular values: an 'X' symbol should be placed in the relevant shaded cells to
indicate the action that will be executed for the given conditions. Some of the
shaded cells will need to be left empty.
(2)
(c) Dry run the algorithm above by completing Table 2. The first row has been
completed for you.
Table 2
Page 76 of 210
x c b a
Printed
output
0 0 0 0 000
(5)
___________________________________________________________________
___________________________________________________________________
(1)
(Total 10 marks)
Q35.
Create a folder / directory for your new program.
The algorithm, represented the using pseudo-code below, and the variable table
underneath, describe the process of using a check digit to check if a value entered by the
user is a valid 13 digit International Standard Book Number (ISBN).
FOR Count ←
1 TO 13 DO
OUTPUT "Please enter next digit of ISBN: "
INPUT ISBN[Count]
ENDFOR
CalculatedDigit ← 0
Count ←1
WHILE Count
CalculatedDigit ← CalculatedDigit + ISBN[Count]
Count ← Count + 1
Count ←
Count + 1
ENDWHILE
WHILE CalculatedDigit >= 10 DO
CalculatedDigit ← CalculatedDigit – 10
ENDWHILE
Page 77 of 210
CalculatedDigit ←
10 – CalculatedDigit
IF CalculatedDigit = 10
THEN CalculatedDigit 0 ←
ENDIF
IF CalculatedDigit = ISBN[13]
THEN OUTPUT "Valid ISBN"
ELSE OUTPUT "Invalid ISBN"
ENDIF
Your evidence must show the result of the test and, as a minimum, the last three
digits entered for the test.
(2)
Your evidence must show the result of the test and, as a minimum, the last three
digits entered for the test.
(1)
(Total 18 marks)
Page 78 of 210
Mark schemes
Q1.
All marks AO1 (knowledge)
local variables;
return address;
parameters;
register values; A. example of register that would be in stack frame
Max 2
[2]
Q2.
(a) All marks AO2 (analyse)
1 2 3 4 5 6
1 0 2 5 3 0 8
2 2 0 1 0 0 0
3 5 1 0 0 0 4
4 3 0 0 0 1 0
5 0 0 0 1 0 5
6 8 0 4 0 5 0
Alternative answer
1 2 3 4 5 6
1 0 2 5 3 0 8
2 0 1 0 0 0
3 0 0 0 4
4 0 1 0
5 0 5
6 0
Alternative answer
1 2 3 4 5 6
1 0
2 2 0
3 5 1 0
Page 79 of 210
4 3 0 0 0
5 0 0 0 1 0
6 8 0 4 0 5 0
Mark as follows:
I. non-zero symbols used to denote no edge but only for showing no edge
going from a node to itself
2
Adjacency list appropriate when there are few edges between vertices // when
graph/matrix is sparse; NE. few edges
Max 2
2
Mark as follows:
I. output column
1 mark first value of A is 2
1 mark second value of A is 5 and third value is 3
1 mark fourth and subsequent values of A are 8, 3, 7, 4, 9 with no more values
after this
1 mark D[2] is set to 2 and then does not change
Page 80 of 210
1 mark D[3] is set to 5 and then changes to 3 and does not change again
1 mark correct final values for each position of array P
Page 81 of 210
1 mark correct final values for D[1], D[4], D[5], D[6]
Page 82 of 210
Max 6 marks if any errors
7
Used to store the previous node/location in the path (to this node);
Max 1 if not clear that the values represent the shortest path
Page 83 of 210
Alternative answer
Max 1 if not clear that the values represent the shortest path
2
[16]
Q3.
(a) 4 marks for AO3 (design) and 8 marks for AO3 (programming)
Page 84 of 210
Guidance
Note that AO3 (design) points are for selecting appropriate techniques to use
to solve the problem, so should be credited whether the syntax of
programming language statements is correct or not and regardless of whether
the solution works.
Page 85 of 210
answer should be referred to team leader for guidance on how it should be
marked
12
Python 2
import math
again = "y"
while again == "y":
num = int(raw_input("Enter a number: "))
if num > 1:
prime = True
for count in range(2, int(math.sqrt(num)) + 1):
if num % count == 0:
prime = False
if prime == True:
print "Is prime"
else:
print "Is not prime"
else:
print "Not greater than 1"
again = raw_input("Again (y or n)? ")
Python 3
import math
again = "y"
while again == "y":
num = int(input("Enter a number: "))
if num > 1:
prime = True
for count in range(2, int(math.sqrt(num)) + 1):
if num % count == 0:
prime = False
if prime == True:
print("Is prime")
else:
print("Is not prime")
else:
print("Not greater than 1")
again = input("Again (y or n)? ")
Visual Basic
Sub Main()
Dim Again As Char = "y"
Dim Num As Integer
Dim Prime As Boolean
While Again = "y"
Console.Write("Enter a number: ")
Num = Console.ReadLine()
If Num > 1 Then
Prime = True
For Count = 2 To System.Math.Sqrt(Num)
If Num Mod Count = 0 Then
Prime = False
End If
Next
If Prime Then
Console.WriteLine("Is prime")
Else
Console.WriteLine("Is not prime")
End If
Else
Console.WriteLine("Not greater than 1")
End If
Page 86 of 210
Console.Write("Again (y or n)? ")
Again = Console.ReadLine()
End While
End Sub
C#
{
string Again = "Y";
int Num = 0;
bool Prime = true;
while (Again == "Y")
{
Console.Write("Enter a number: ");
Num = Convert.ToInt32(Console.ReadLine());
if (Num > 1)
{
for (int Count = 2; Count < Convert.ToInt32(Math.Sqrt(Num))
+ 1; Count++)
{
if (Num % Count == 0)
{
Prime = false;
}
}
if (Prime == true )
{
Console.WriteLine("Is prime");
}
else
{
Console.WriteLine("Is not prime");
}
}
else
{
Console.WriteLine("Not greater than 1");
}
Console.Write("Again (y or n)? ");
Again = Console.ReadLine().ToUpper();
}
}
Java
public static void main(String[] args)
{
String again;
do
{Console.println("Enter a number:");
int number = Integer.parseInt(Console.readLine());
if(number <= 1)
{
}
else
{
Console.println("Not greater than 1"); boolean prime =
true;
int count = number - 1;
while (prime && count > 1)
{
if(number%count == 0)
{
prime = false;
}
Page 87 of 210
count--;
}
if(prime)
{
Console.println("Is prime");
}
else
{
Console.println("Is not prime");
}
}
Console.println("Would you like to enter another number?
YES/NO");
again = Console.readLine();
} while (again.equals("YES"));
}
Pascal / Delphi
var
again : string;
num, count : integer;
prime : boolean;
begin
again := 'y';
while again = 'y' do
begin
write('Enter a number: ');
readln(num);
if num > 1 then
begin
prime := True;
for count := 2 to round(sqrt(num)) do
if num mod count = 0 then
prime := False;
if prime = true then
writeln('Is prime')
else
writeln('Is not prime');
end
else
writeln('Not greater than 1');
write('Again (y or n)? ');
readln(again);
end;
readln;
end.
Screen captures showing the number 1 being entered with the message “Not
greater than 1” displayed, then the number 5 being entered with the message
“Is prime” displayed and then the number 8 being entered with the message
“Is not prime” being displayed and program stops after user input stating they
do not want to enter another number;
A. alternative messages being displayed if they match code from part (a)
Page 88 of 210
Enter a number: 1
Not greater than 1
Again (y or n)? y
Enter a number: 5
Is prime
Again (y or n)? y
Enter a number: 8
Is not prime
Again (y or n)? n
>>>
1
[13]
Q5.
(a) Mark is for AO2 (analyse)
I. case
I. spacing
R. if any additional code
1
A. MaxSize
I. case
I. spacing
R. if any additional code
R. if spelt incorrectly
1
Mark as follows
• Check for 1st mark point from either solution 1 or solution 2.
• 2nd mark point for Solution 1 only to be awarded if 1st mark point for
Solution 1 has been awarded.
• 2nd mark point for Solution 2 only to be awarded if 1st mark point for
Solution 2 has been awarded
Solution 1
1st mark:
With a linear queue there could be locations available that are not able to be
used A. there could be wasted space
(where there is space available in the data structure but it is unusable as it is
in front of the data items in the queue);
2nd mark:
(To avoid this issue) items in the queue are all shuffled forward when an item
is deleted from (the front of the) queue;
//
Page 89 of 210
Circular lists “wrap round” so (avoid this problem as) the front of the queue
does not have to be in the first position in the data structure;
Solution 2
1st mark:
Items in a linear queue are all shuffled forward when an item is deleted from
(the front);
//
No need to shuffle items forward after deleting an item in a circular queue;
2nd mark:
this makes (deleting from) (large) linear lists time inefficient;
//
meaning circular queues are more time efficient (when deleting);
2
The queue is small in size (so the time inefficiency is not significant);
1
Otherwise generate a random number from the other numbers between 0 and
25 // otherwise generate a random number from those equivalent to non
1-point tiles;
Note for examiners: refer unusual answers that would work to team leader
4
Subtract 32 from the character code // AND the character code with the bit
pattern 1011111 / 11011111 // AND the character code with (the decimal
value) 95 / 223;
A. Hexadecimal equivalents
Convert that value back into a character and replace the current character with
the new character;
Page 90 of 210
existing string
Alternative answer
Using a list of the lowercase letters and a list of the uppercase letters;
Find the index of the lowercase letter in the list of lowercase letters;
Get the character in the corresponding position in the uppercase list and
replace the current character with the new character;
Q6.
(a) (i) Mark is for AO3 (programming)
Python 2
def CreateTileDictionary():
TileDictionary = dict()
for Count in range(26):
if Count in [0, 4, 8, 13, 14, 17, 18, 19]:
TileDictionary[chr(65 + Count)] = 1
elif Count in [1, 2, 3, 6, 11, 12, 15, 20]:
TileDictionary[chr(65 + Count)] = 2
elif Count in [5, 7, 10, 21, 22, 24]:
TileDictionary[chr(65 + Count)] = 3
elif Count in [9, 23]:
TileDictionary[chr(65 + Count)] = 4
else:
TileDictionary[chr(65 + Count)] = 5
return TileDictionary
Python 3
def CreateTileDictionary():
TileDictionary = dict()
for Count in range(26):
if Count in [0, 4, 8, 13, 14, 17, 18, 19]:
TileDictionary[chr(65 + Count)] = 1
elif Count in [1, 2, 3, 6, 11, 12, 15, 20]:
TileDictionary[chr(65 + Count)] = 2
elif Count in [5, 7, 10, 21, 22, 24]:
TileDictionary[chr(65 + Count)] = 3
elif Count in [9, 23]:
TileDictionary[chr(65 + Count)] = 4
else:
TileDictionary[chr(65 + Count)] = 5
return TileDictionary
Visual Basic
Page 91 of 210
Function CreateTileDictionary() As Dictionary(Of Char,
Integer)
Dim TileDictionary As New Dictionary(Of Char, Integer)()
For Count = 0 To 25
If Array.IndexOf({0, 4, 8, 13, 14, 17, 18, 19}, Count)
> -1 Then
TileDictionary.Add(Chr(65 + Count), 1)
ElseIf Array.IndexOf({1, 2, 3, 6, 11, 12, 15, 20}, Count)
> -1 Then
TileDictionary.Add(Chr(65 + Count), 2)
ElseIf Array.IndexOf({5, 7, 10, 21, 22, 24},
Count) > -1 Then
TileDictionary.Add(Chr(65 + Count), 3)
ElseIf Array.IndexOf({9, 23}, Count) > -1 Then
TileDictionary.Add(Chr(65 + Count), 4)
Else
TileDictionary.Add(Chr(65 + Count), 5)
End If
Next
Return TileDictionary
End Function
C#
private static void CreateTileDictionary(ref Dictionary<char,
int> TileDictionary)
{
int[] Value1 = { 0, 4, 8, 13, 14, 17, 18, 19 };
int[] Value2 = { 1, 2, 3, 6, 11, 12, 15, 20 };
int[] Value3 = { 5, 7, 10, 21, 22, 24 };
int[] Value4 = { 9, 23 };
Java
Map createTileDictionary()
{
Map<Character,Integer> tileDictionary = new
HashMap<Character,Integer>();
for (int count = 0; count < 26; count++)
{
Page 92 of 210
switch (count) {
case 0:
case 4:
case 8:
case 13:
case 14:
case 17:
case 18:
case 19:
tileDictionary.put((char)(65 + count), 1);
break;
case 1:
case 2:
case 3:
case 6:
case 11:
case 12:
case 15:
case 20:
tileDictionary.put((char)(65 + count), 2);
break;
case 5:
case 7:
case 10:
case 21:
case 22:
case 24:
tileDictionary.put((char)(65 + count), 3);
break;
case 9:
case 23:
tileDictionary.put((char)(65 + count), 4);
break;
default:
tileDictionary.put((char)(65 + count), 5);
break;
}
}
return tileDictionary;
}
Pascal / Delphi
function CreateTileDictionary() : TTileDictionary;
var
TileDictionary : TTileDictionary;
Count : integer;
begin
TileDictionary := TTileDictionary.Create();
for Count := 0 to 25 do
begin
case count of
0, 4, 8, 13, 14, 17, 18, 19:
TileDictionary.Add(chr(65 + count), 1);
1, 2, 3, 6, 11, 12, 15, 20: TileDictionary.Add(chr(65
+ count), 2);
5, 7, 10, 21, 22, 24: TileDictionary.Add(chr(65 +
count), 3);
9, 23: TileDictionary.Add(chr(65 + count), 4);
else TileDictionary.Add(chr(65 + count), 5);
end;
end;
CreateTileDictionary := TileDictionary;
end;
Page 93 of 210
(ii) Mark is for AO3 (evaluate)
Screen captures showing the requested test being performed and the
correct points values for J, X, Z and Q are shown; I. order of letters
TILE VALUES
Points for X: 4
Points for R: 1
Points for Q: 5
Points for Z: 5
Points for M: 2
Points for K: 3
Points for A: 1
Points for Y: 3
Points for L: 2
Points for I: 1
Points for F: 3
Points for H: 3
Points for D: 2
Points for U: 2
Points for N: 1
Points for V: 3
Points for T: 1
Points for E: 1
Points for W: 3
Points for C: 2
Points for G: 2
Points for P: 2
Points for J: 4
Points for O: 1
Points for B: 2
Points for S: 1
Either:
enter the word you would like to play OR
press 1 to display the letter values OR
press 4 to view the tile queue OR
press 7 to view your tiles again OR
press 0 to fill hand and stop the game.
1
Page 94 of 210
Python 2
…
StartHandSize = int(raw_input("Enter start hand size: "))
while StartHandSize < 1 or StartHandSize > 20:
StartHandSize = int(raw_input("Enter start hand size: "))
…
Python 3
…
StartHandSize = int(input("Enter start hand size: "))
while StartHandSize < 1 or StartHandSize > 20:
StartHandSize = int(input("Enter start hand size: "))
…
Visual Basic
…
Do
Console.Write("Enter start hand size: ")
StartHandSize = Console.ReadLine()
Loop Until StartHandSize >= 1 And StartHandSize <= 20
…
C#
…
do
{
Console.Write("Enter start hand size: ");
StartHandSize = Convert.ToInt32(Console.ReadLine());
} while (StartHandSize < 1 || StartHandSize > 20);
…
Java
…
do {
Console.println(&"Enter start hand size: &");
startHandSize = Integer.parseInt(Console.readLine());
} while (startHandSize < 1 || startHandSize > 20);
…
Pascal / Delphi
…
StartHandSize := 0;
Choice := '';
while (StartHandSize < 1) or (StartHandSize > 20) do
begin
write('Enter start hand size: ');
readln(StartHandSize);
end;
…
Screen capture(s) showing that after the values 0 and 21 are entered the
user is asked to enter the start hand size again and then the menu is
displayed;
++++++++++++++++++++++++++++++++++++++
Page 95 of 210
+ Welcome to the WORDS WITH AQA game +
++++++++++++++++++++++++++++++++++++++
=========
MAIN MENU
=========
1. Create variables to store the current start, mid and end points; A. no
variable for midpoint if midpoint is calculated each time it is needed in
the code
2. Setting correct initial values for start and end variables;
3. Iterative structure with one correct condition (either word is valid or
start is greater than end); R. if code is a linear search
4. Iterative structure with 2nd correct condition and correct logic;
5. Inside iterative structure, correctly calculate midpoint between start
and end;
A. mid-point being either the position before or the position after
the exact middle if calculated midpoint is not a whole number R. if
midpoint is sometimes the position before and sometimes the
position after the exact middle R. if not calculated under all
circumstances when it should be
6. Inside iterative structure there is a selection structure that
compares word at midpoint position in list with word being
searched for;
7. Values of start and end changed correctly under correct
circumstances;
8. True is returned if match with midpoint word found and True is not
returned under any other circumstances;
1. Create variable to store the current midpoint, start and end points
passed as parameters to subroutine; A. no variable for midpoint if
midpoint is calculated each time it is needed in the code A. midpoint as
parameter instead of as local variable
2. Initial subroutine call has values of 0 for startpoint parameter and
number of words in AllowedWords for endpoint parameter;
3. Selection structure which contains recursive call if word being
Page 96 of 210
searched for is after word at midpoint;
4. Selection structure which contains recursive call if word being
searched for is before word at midpoint;
5. Correctly calculate midpoint between start and end;
A. midpoint being either the position before or the position after the
exact middle if calculated midpoint is not a whole number R. if
midpoint is sometimes the position before and sometimes the
position after the exact middle R. if not calculated under all
circumstances when it should be
6. There is a selection structure that compares word at midpoint
position in list with word being searched for and there is no
recursive call if they are equal with a value of True being returned;
7. In recursive calls the parameters for start and end points have
correct values;
8. There is a selection structure that results in no recursive call and
False being returned if it is now known that the word being
searched for is not in the list;
Python 2
def CheckWordIsValid(Word, AllowedWords):
ValidWord = False
Start = 0
End = len(AllowedWords) - 1
while not ValidWord and Start <= End:
Mid = (Start + End) // 2
print AllowedWords[Mid]
if AllowedWords[Mid] == Word:
ValidWord = True
elif Word > AllowedWords[Mid]:
Start = Mid + 1
else:
End = Mid - 1
return ValidWord
Python 3
def CheckWordIsValid(Word, AllowedWords):
ValidWord = False
Start = 0
End = len(AllowedWords) - 1
while not ValidWord and Start <= End:
Mid = (Start + End) // 2
print(AllowedWords[Mid])
if AllowedWords[Mid] == Word:
ValidWord = True
Page 97 of 210
elif Word > AllowedWords[Mid]:
Start = Mid + 1
else:
End = Mid - 1
return ValidWord
Visual Basic
Function CheckWordIsValid(ByVal Word As String, ByRef
AllowedWords As List(Of String)) As Boolean
Dim ValidWord As Boolean = False
Dim LStart As Integer = 0
Dim LMid As Integer
Dim LEnd As Integer = Len(AllowedWords) - 1
While Not ValidWord And LStart <= LEnd
LMid = (LStart + LEnd) \ 2
Console.WriteLine(AllowedWords(LMid))
If AllowedWords(LMid) = Word Then
ValidWord = True
ElseIf Word > AllowedWords(LMid) Then
LStart = LMid + 1
Else
LEnd = LMid - 1
End If
End While
Return ValidWord
End Function
C#
private static bool CheckWordIsValid(string Word,
List<string> AllowedWords)
{
bool ValidWord = false;
int Start = 0;
int End = AllowedWords.Count - 1;
int Mid = 0;
while (!ValidWord && Start <= End)
{
Mid = (Start + End) / 2;
Console.WriteLine(AllowedWords[Mid]);
if (AllowedWords[Mid] == Word)
{
ValidWord = true;
}
else if (string.Compare(Word, AllowedWords[Mid]) > 0)
{
Start = Mid + 1;
}
else
{
End = Mid -1;
}
}
return ValidWord;
}
Java
boolean checkWordIsValid(String word, String[] allowedWords)
{
boolean validWord = false;
int start = 0;
int end = allowedWords.length - 1;
int mid = 0;
while (!validWord && start <= end)
Page 98 of 210
{
mid = (start + end) / 2;
Console.println(allowedWords[mid]);
if (allowedWords[mid].equals(word))
{
validWord = true;
}
else if (word.compareTo(allowedWords[mid]) > 0)
{
start = mid + 1;
}
else
{
end = mid -1;
}
}
return validWord;
}
Pascal / Delphi
function CheckWordIsValid(Word : string; AllowedWords : array
of string) : boolean;
var
ValidWord : boolean;
Start, Mid, EndValue : integer;
begin
ValidWord := False;
Start := 0;
EndValue := length(AllowedWords) - 1;
while (not(ValidWord)) and (Start <= EndValue) do
begin
Mid := (Start + EndValue) div 2;
writeln(AllowedWords[Mid]);
if AllowedWords[Mid] = Word then
ValidWord := True
else if Word > AllowedWords[Mid] then
Start := Mid + 1
else
EndValue := Mid - 1;
end;
CheckWordIsValid := ValidWord;
end;
Screen capture(s) showing that the word “jars” was entered and the
words “MALEFICIAL”, “DONGLES”, “HAEMAGOGUE”,
“INTERMINGLE”, “LAGGER”, “JOULED”, “ISOCLINAL”, “JAUKING”,
“JACARANDA”, “JAMBEUX”, “JAPONICA”, “JAROVIZE”, “JASPER”,
“JARTA”, “JARRAH”, “JARRINGLY”, “JARS” are displayed in that order;
Page 99 of 210
alternative answer for mark point 5 in part (c)(i) used
Screen capture(s) showing that the word “jars” was entered and the
words “MALEATE”, “DONDER”, “HADST”, “INTERMENDIS”, “LAGAN”,
“JOTTERS”, “ISOCHROMATIC”, “JASPERS”, “JABBING”, “JALOUSIE”,
“JAPANISES”, “JARGOONS”, “JARRED”, “JASIES”, “JARUL”, “JARS”
are displayed in that order;
Screen capture(s) showing that the word “jars” was entered and the
words “LAMP”, “DESK”, “GAGE”, “IDEAS”, “INVITAT ION”,
“JOURNALS”, “JAMAICA”, “JEWELLERY”, “JEAN”, “JAR”, “JAY”,
“JASON”, “JARS” are displayed in that order;
Either:
enter the word you would like to play OR
press 1 to display the letter values OR
press 4 to view the tile queue OR
press 7 to view your tiles again OR
press 0 to fill hand and stop the game.
>jars
MALEFICIAL
DONGLES
HAEMAGOGUE
INTERMINGLE
LAGGER
JOULED
ISOCLINAL
JAUKING
JACARANDA
JAMBEUX
JAPONICA
JAROVIZE
JASPER
JARTA
JARRAH
JARRINGLY
JARS
Valid word
Alternative answer
If answer looks at each letter in AllowedWords in turn and maintains a
count (eg in array/list) for the number of each letter found then mark
points 2 and 5 should be:
2. Creation of suitable data structure to store 26 counts.
Python 2
def CalculateFrequencies(AllowedWords):
print "Letter frequencies in the allowed words are:"
for Code in range (26):
LetterCount = 0
LetterToFind = chr(Code + 65)
for Word in AllowedWords:
for Letter in Word:
if Letter == LetterToFind:
b>LetterCount += 1
sys.stdout.write(LetterToFind + " " + LetterCount)
Alternative answer
def CalculateFrequencies(AllowedWords):
for Letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
Count=0
for Word in AllowedWords:
Alternative answer
def CalculateFrequencies(AllowedWords):
Counts = []
for a in range(26):
Counts.append(0)
for Word in AllowedWords:
for Letter in Word:
Counts[ord(Letter) - 65] += 1
for a in range(26):
sys.stdout.write(chr(a + 65) + " " + str(Counts[a]))
Python 3
def CalculateFrequencies(AllowedWords):
print("Letter frequencies in the allowed words are:")
for Code in range (26):
LetterCount = 0
LetterToFind = chr(Code + 65)
for Word in AllowedWords:
for Letter in Word:
if Letter == LetterToFind:
LetterCount += 1
print(LetterToFind, " ", LetterCount)
Alternative answer
def CalculateFrequencies(AllowedWords):
for Letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
Count=0
for Word in AllowedWords:
NumberOfTimes = Word.count(Letter)
Count = Count + NumberOfTimes
print(Letter,Count)
Alternative answer
def CalculateFrequencies(AllowedWords):
Counts = []
for a in range(26):
Counts.append(0)
for Word in AllowedWords:
for Letter in Word:
Counts[ord(Letter) - 65] += 1
for a in range(26):
print(chr(a + 65), Counts[a])
Visual Basic
Sub CalculateFrequencies(ByRef AllowedWords As List(Of
String))
Dim LetterCount As Integer
Dim LetterToFind As Char
Console.WriteLine("Letter frequencies in the allowed words
are:")
Alternative answer
Sub CalculateFrequencies(ByRef AllowedWords As List(Of
String))
Dim NumberOfTimes, Count As Integer
Console.WriteLine("Letter frequencies in the allowed words
are:")
For Each Letter In "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Count = 0
For Each Word In AllowedWords
NumberOfTimes = Word.Split(Letter).Length - 1
Count += NumberOfTimes
Next
Console.WriteLine(Letter & " " & Count)
Next
End Sub
Alternative answer
Sub CalculateFrequencies(ByRef AllowedWords As List(Of
String))
Dim Counts(25) As Integer
For Count = 0 To 25
Counts(Count) = 0
Next
Console.WriteLine("Letter frequencies in the allowed words
are:")
For Each Word In AllowedWords
For Each Letter In Word
Counts(Asc(Letter) - 65) += 1
Next
Next
For count = 0 To 25
Console.WriteLine(Chr(count + 65) & " " & Counts(count))
Next
End Sub
Alternative answer
private static void CalculateFrequencies(List<string>
AllowedWords)
{
Console.WriteLine("Letter frequencies in the allowed words
are:");
int LetterCount = 0;
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
foreach (var Letter in Alphabet)
{
LetterCount = 0;
foreach (var Words in AllowedWords)
{
LetterCount = LetterCount + (Words.Split(Letter).Length
- 1);
}
Console.WriteLine(Letter + " " + LetterCount);
}
}
Java
void calculateFrequencies(String[] allowedWords)
{
int letterCount;
char letterToFind;
for (int count = 0; count < 26; count++)
{
letterCount = 0;
letterToFind = (char)(65 + count);
for(String word:allowedWords)
{
for(char letter : word.toCharArray())
{
if(letterToFind == letter)
{
letterCount++;
}
}
}
Console.println(letterToFind + ", Frequency: " +
letterCount);
}
}
Alternative answer
Alternative answer
void calculateFrequencies(String[] allowedWords)
{
int[] counts = new int[26];
for(String word: allowedWords)
{
for(char letter: word.toCharArray())
{
int letterPostion = (int)letter - 65;
counts[letterPostion]++;
}
}
for (int count = 0; count < 26; count++)
{
char letter = (char)(65 + count);
Console.println(letter + ", Frequency: " + counts[count]);
}
}
Pascal / Delphi
procedure CalculateFrequencies(AllowedWords : array of
string);
var
Code, LetterCount : integer;
LetterToFind, Letter : char;
Word : string;
begin
writeln('Letter frequencies in the allowed words are:');
for Code := 0 to 25 do
begin
LetterCount := 0;
LetterToFind := chr(65 + Code);
for Word in AllowedWords do
begin
for Letter in Word do
begin
if Letter = LetterToFind then
LetterCount := LetterCount + 1;
end;
end;
writeln(LetterToFind, ' ', LetterCount);
end;
end;
Either:
enter the word you would like to play OR
press 1 to display the letter values OR
press 4 to view the tile queue OR
press 7 to view your tiles again OR
press 0 to fill hand and stop the game.
>
Letter frequencies in the allowed words are:
A 5299
B 1105
C 2980
D 2482
E 7523
F 909
G 1692
H 1399
I 5391
J 178
K 569
L 3180
M 1871
N 4762
O 4177
P 1992
Q 122
R 4812
S 4999
T 4695
U 1898
V 835
W 607
X 246
Y 999
Z 128
Either:
enter the word you would like to play OR
press 1 to display the letter values OR
press 4 to view the tile queue OR
press 7 to view your tiles again OR
press 0 to fill hand and stop the game.
>
1
Mark points 1-5 same as for recursive attempt. No marks awarded for
mark points 6-11, instead award marks as appropriate for mark points
12-14.
12. Adds the score for the original word to the score once // sets the
initial score to be the score for the original word; A. no call to
subroutine GetScoreForWord if correct code to calculate score
included in sensible place in GetScoreForWordAndPrefix
subroutine. Note for examiners: there is no need for the answer
to check if the original word is valid
13. Iterative structure that will repeat n − 1 times where n is the length
of the word; A. n − 2 A. n
14. Inside iterative structure adds score for current prefix word, if it is a
valid word, to score once; A. no call to GetScoreForWord if own
code to calculate score is correct
Python 2
def UpdateAfterAllowedWord(Word, PlayerTiles, PlayerScore,
Alternative answer
def GetScoreForWordAndPrefix(Word,TileDictionary,
AllowedWords):
Score = 0
if CheckWordIsValid(Word,AllowedWords):
Score += GetScoreForWord(Word, TileDictionary)
if len(Word[:-1]) > 0:
Score +=GetScoreForWordAndPrefix(Word[:-1],
TileDictionary,AllowedWords)
return Score
Python 3
def UpdateAfterAllowedWord(Word, PlayerTiles, PlayerScore,
PlayerTilesPlayed, TileDictionary, AllowedWords):
PlayerTilesPlayed += len(Word)
for Letter in Word:
PlayerTiles = PlayerTiles.replace(Letter, "", 1)
PlayerScore += GetScoreForWordAndPrefix(Word,
TileDictionary, AllowedWords)
return PlayerTiles, PlayerScore, PlayerTilesPlayed
Alternative answer
def GetScoreForWordAndPrefix(Word,TileDictionary,
AllowedWords):
Score = 0
if CheckWordIsValid(Word,AllowedWords):
Score += GetScoreForWord(Word, TileDictionary)
if len(Word[:-1]) > 0:
Score +=GetScoreForWordAndPrefix(Word[:-1],
TileDictionary,AllowedWords)
Visual Basic
Sub UpdateAfterAllowedWord(ByVal Word As String, ByRef
PlayerTiles As String, ByRef PlayerScore As Integer, ByRef
PlayerTilesPlayed As Integer, ByVal TileDictionary As
Dictionary(Of Char, Integer), ByRef AllowedWords As List(Of
String))
PlayerTilesPlayed += Len(Word)
For Each Letter In Word
PlayerTiles = Replace(PlayerTiles, Letter, "", , 1)
Next
PlayerScore += GetScoreForWordAndPrefix(Word,
TileDictionary, AllowedWords)
End Sub
Alternative answer
Function GetScoreForWordAndPrefix(ByVal Word As String, ByVal
TileDictionary As Dictionary(Of Char, Integer), ByRef
AllowedWords As List(Of String)) As Integer
Dim Score As Integer = 0
If CheckWordIsValid(Word, AllowedWords) Then
Score += GetScoreForWord(Word, TileDictionary)
End If
If Len(Word) - 1 > 0 Then
Score += GetScoreForWordAndPrefix(Mid(Word, 1, Len(Word)
- 1), TileDictionary, AllowedWords)
End If
Return Score
End Function
C#
private static void UpdateAfterAllowedWord(string Word, ref
string PlayerTiles, ref int PlayerScore, ref int
PlayerTilesPlayed, Dictionary<char, int> TileDictionary,
List<string> AllowedWords)
{
PlayerTilesPlayed = PlayerTilesPlayed + Word.Length;
foreach (var Letter in Word)
{
PlayerTiles =
PlayerTiles.Remove(PlayerTiles.IndexOf(Letter), 1);
}
PlayerScore = PlayerScore + GetScoreForWordAndPrefix(Word,
TileDictionary, AllowedWords);
}
Alternative answer
private static int GetScoreForWordAndPrefix(string Word,
Dictionary<char, int> TileDictionary, List<string>
AllowedWords)
{
int Score = 0;
if (CheckWordIsValid(Word, AllowedWords))
{
Score = Score + GetScoreForWord(Word, TileDictionary);
}
if (Word.Remove(Word.Length - 1).Length > 0)
{
Score = Score +
GetScoreForWordAndPrefix(Word.Remove(Word.Length - 1),
TileDictionary, AllowedWords);
}
return Score;
}
Java
int getScoreForWordAndPrefix(String word, Map tileDictionary,
String[] allowedWords)
{
int score = 0;
if(word.length() < 2)
{
return 0;
}
else
{
if(checkWordIsValid(word, allowedWords))
{
score = getScoreForWord(word, tileDictionary);
}
word = word.substring(0, word.length()-1);
return score + getScoreForWordAndPrefix(word,
tileDictionary, allowedWords);
}
}
Alternative answer
int getScoreForWordAndPrefix(String word, Map tileDictionary,
String[] allowedWords)
{
int score = 0;
if(checkWordIsValid(word, allowedWords))
{
score += getScoreForWord(word, tileDictionary);
}
word = word.substring(0, word.length()-1);
if(word.length()>1)
{
score += getScoreForWordAndPrefix(word, tileDictionary,
allowedWords);
}
return score;
}
Pascal / Delphi
function GetScoreForWordAndPrefix(Word : string;
TileDictionary : TileDictionary; AllowedWords : array of
string) : integer;
var
Score : integer;
begin
if length(word) <= 1 then
Score := 0
else
begin
Score := 0;
if CheckWordIsValid(Word, AllowedWords) then
Score := Score + GetScoreForWord(Word,
TileDictionary);
Delete(Word,length(Word),1);
Score := Score + GetScoreForWordAndPrefix(Word,
TileDictionary, AllowedWords);
end;
GetScoreForWordAndPrefix := Score;
end;
Screen capture(s) showing that the word abandon was entered and the
new score of 78 is displayed;
Q7.
(a) Mark is for AO1 (knowledge)
MAX 2 if any errors eg additional outputs / function calls after output of Phil
Q8.
(a) (i) Marks are for AO3 (programming)
1 mark: 1. tests for lower bound and displays error message if below
1 mark: 2. tests for upper bound and displays error message if above
1 mark: 3. Upper bound test uses LandscapeSize instead of data value
of 14/15 A. in use of incorrect condition
1 mark: 4. 1-3 happen repeatedly until valid input (for the upper and
lower bounds used in the code provided) and forces re-entry of data
each time
VB.NET
Do
Console.Write(" Input " & CoordinateName & " coordinate: ")
Coordinate = CInt(Console.ReadLine())
If Coordinate < 0 Or Coordinate >= LandscapeSize Then
Console.WriteLine("Coordinate is outside of landscape,
please try again.")
End If
Loop While Coordinate < 0 Or Coordinate >= LandscapeSize
Alternative answer
Do
Console.Write(" Input " & CoordinateName & " coordinate: ")
Coordinate = CInt(Console.ReadLine())
If Coordinate < 0 Or Coordinate >= LandscapeSize Then
Console.WriteLine("Coordinate is outside of landscape,
please try again.")
End If
Loop Until Coordinate >= 0 And Coordinate < LandscapeSize
PYTHON 2
def __InputCoordinate(self, CoordinateName):
Coordinate = int(raw_input(" Input " + CoordinateName + "
coordinate:"))
while Coordinate < 0 or Coordinate >= self.__LandscapeSize:
Coordinate = int(raw_input("Coordinate is outside of
landscape, please try again."))
return Coordinate
PYTHON 3
def __InputCoordinate(self, CoordinateName):
Coordinate = int(input(" Input " + CoordinateName + "
coordinate:"))
while Coordinate < 0 or Coordinate >= self.__LandscapeSize:
Coordinate = int(input("Coordinate is outside of
C#
do
{
Console.Write(" Input " + Coordinatename + " coordinate: ");
Coordinate = Convert.ToInt32(Console.ReadLine());
if ((Coordinate < 0) || (Coordinate >= LandscapeSize))
{
Console.WriteLine("Coordinate is outside of landscape,
please try again.");
}
} while ((Coordinate < 0) || (Coordinate >= LandscapeSize));
PASCAL
repeat
write(' Input ' , CoordinateName, ' coordinate: ');
readln(Coordinate);
if (Coordinate < 0) or (Coordinate >= LandscapeSize) then
writeln('Coordinate is outside of landscape, please try
again.');
until (Coordinate >= 0) and (Coordinate < LandscapeSize);
JAVA
private int InputCoordinate(char CoordinateName)
{
int Coordinate;
do
{
Coordinate = Console.readInteger(" Input " +
CoordinateName + " coordinate: ");
if (Coordinate >= LandscapeSize || Coordinate < 0)
{
Console.println("Coordinate is outside of landscape,
please try again.");
}
}while (Coordinate >= LandscapeSize || Coordinate < 0);
return Coordinate;
}
****SCREEN CAPTURE(S)****
Must match code from part (a)(i), including error message. Code for part
(a)(i) must be sensible.
1 mark: New subroutine created, with correct name, that overrides the
subroutine in the Animal class
I. private, protected, public modifiers
VB.NET
Public Overrides Sub CalculateNewAge()
MyBase.CalculateNewAge()
If Gender = Genders.Male Then
ProbabilityOfDeathOtherCauses =
ProbabilityOfDeathOtherCauses * 1.5
Else
If Age >= 2 Then
ProbabilityOfDeathOtherCauses =
ProbabilityOfDeathOtherCauses + 0.05
End If
End If
End Sub
PYTHON 2
def CalculateNewAge(self):
super(Rabbit, self).CalculateNewAge()
if self.__Gender == Genders.Male:
self._ProbabilityOfDeathOtherCauses =
self._ProbabilityOfDeathOtherCauses * 1.5
else:
if self._Age >= 2:
self._ProbabilityOfDeathOtherCauses =
self._ProbabilityOfDeathOtherCauses + 0.05
PYTHON 3
def CalculateNewAge(self):
super(Rabbit, self).CalculateNewAge()
if self.__Gender == Genders.Male:
self._ProbabilityOfDeathOtherCauses =
self._ProbabilityOfDeathOtherCauses * 1.5
else:
if self._Age >= 2:
self._ProbabilityOfDeathOtherCauses =
self._ProbabilityOfDeathOtherCauses + 0.05
C#
public override void CalculateNewAge()
{
base.CalculateNewAge();
if (Gender == Genders.Male)
PASCAL
Procedure Rabbit.CalculateNewAge();
begin
inherited;
if Gender = Male then
ProbabilityOfDeathOtherCauses :=
ProbabilityOfDeathOtherCauses * 1.5
else
if Age >= 2 then
ProbabilityOfDeathOtherCauses :=
ProbabilityOfDeathOtherCauses + 0.05;
end;
JAVA
@Override
public void CalculateNewAge()
{
super.CalculateNewAge();
if (Gender == Genders.Male)
{
ProbabilityOfDeathOtherCauses *= 1.5;
}
else if(Age >= 2)
{
ProbabilityOfDeathOtherCauses += 0.05;
}
}
****SCREEN CAPTURE(S)****
Must match code from part (b)(i). Code for part (b)(i) must be sensible.
Example:
VB.NET
Class Location
Public Fox As Fox
Public Warren As Warren
Public Terrain As Char
End Sub
End Class
PYTHON 2
class Location:
def __init__(self, TerrainType):
self.Fox = None
self.Warren = None
self.Terrain = TerrainType
PYTHON 3
class Location:
def __init__(self, TerrainType):
self.Fox = None
self.Warren = None
self.Terrain = TerrainType
C#
class Location
{
public Fox Fox;
public Warren Warren;
public char Terrain;
PASCAL
type
Location = class
Fox : Fox;
Warren : Warren;
Terrain : char;
constructor New(TerrainType : char);
end;
1 mark: 1. An indicator for type of terrain will be stored for every location
I. wrong type of terrain in a location
R. if indicators other than R or L used
I. case of indicators
VB.NET
For x = 0 To LandscapeSize - 1
For y = 0 To LandscapeSize - 1
If x = 5 Or y = 2 Then
Landscape(x, y) = New Location("R")
Else
Landscape(x, y) = New Location("L")
End If
Next
Next
PYTHON 2
def __CreateLandscapeAndAnimals(self, InitialWarrenCount,
InitialFoxCount, FixedInitialLocations):
for x in range (0, self.__LandscapeSize):
for y in range (0, self.__LandscapeSize):
if x == 5 or y == 2:
self.__Landscape[x][y] = Location("R")
else:
self.__Landscape[x][y] = Location("L")
if FixedInitialLocations:
...
PYTHON 3
def __CreateLandscapeAndAnimals(self, InitialWarrenCount,
InitialFoxCount, FixedInitialLocations):
for x in range (0, self.__LandscapeSize):
for y in range (0, self.__LandscapeSize):
if x == 5 or y == 2:
self.__Landscape[x][y] = Location("R")
else:
self.__Landscape[x][y] = Location("L")
if FixedInitialLocations:
C#
for (int x = 0; x < LandscapeSize; x++)
{
for (int y = 0; y < LandscapeSize; y++)
{
if ((x == 5) || (y == 2))
{
Landscape[x, y] = new Location('R');
}
else
{
Landscape[x, y] = new Location('L');
}
}
}
PASCAL
for x := 0 to LandscapeSize - 1 do
for y := 0 to LandscapeSize - 1 do
if (x = 5) or (y = 2) then
Landscape[x][y] := Location.New('R')
else
Landscape[x][y] := Location.New('L');
JAVA
for(int x = 0 ; x < LandscapeSize; x++)
{
for(int y = 0; y < LandscapeSize; y++)
{
if(x==5||y==2)
{
Landscape[x][y] = new Location('R');
}
else
{
Landscape[x][y] = new Location('L');
}
}
}
VB.NET
Private Sub DrawLandscape()
Console.WriteLine()
Console.WriteLine("TIME PERIOD: " & TimePeriod)
Console.WriteLine()
Console.Write(" ")
PYTHON 2
def __DrawLandscape(self):
print
print "TIME PERIOD:", str(self.__TimePeriod)
print
sys.stdout.write(" ")
for x in range (0, self.__LandscapeSize):
sys.stdout.write(" ")
if x < 10:
sys.stdout.write(" ")
sys.stdout.write(str(x) + " |")
print
for x in range (0, self.__LandscapeSize * 5 + 3): #CHANGED
4 TO 5
sys.stdout.write("-")
print
for y in range (0, self.__LandscapeSize):
if y < 10:
sys.stdout.write(" ")
sys.stdout.write(str(y) + "|")
for x in range (0, self.__LandscapeSize):
if not self.__Landscape[x][y].Warren is None:
if self.__Landscape[x][y].Warren.GetRabbitCount() <
10:
sys.stdout.write(self.__Landscape[x][y].Warren.GetRabbitCou
nt())
else:
sys.stdout.write(" ")
if not self.__Landscape[x][y].Fox is None:
sys.stdout.write("F")
else:
sys.stdout.write(" ")
sys.stdout.write(self.__Landscape[x][y].Terrain)
sys.stdout.write("|")
print
PYTHON 3
def __DrawLandscape(self):
print()
print("TIME PERIOD:", self.__TimePeriod)
print()
print(" ", end = "")
for x in range (0, self.__LandscapeSize):
print(" ", end = "")
if x < 10:
print(" ", end = "")
print(x, "|", end = "")
print()
for x in range (0, self.__LandscapeSize * 5 + 3): #CHANGE
print("-", end = "")
print()
for y in range (0, self.__LandscapeSize):
if y < 10:
print(" ", end = "")
print("", y, "|", sep = "", end = "")
for x in range (0, self.__LandscapeSize):
if not self.__Landscape[x][y].Warren is None:
if self.__Landscape[x][y].Warren.GetRabbitCount() <
10:
print(" ", end = "")
print(self.__Landscape[x][y].Warren.GetRabbitCount(
), end = "")
else:
print(" ", end = "")
if not self.__Landscape[x][y].Fox is None:
print("F", end = "")
else:
print(" ", end = "")
print(self.__Landscape[x][y].Terrain, end = "")
print("|", end = "")
print()
C#
private void DrawLandscape()
{
Console.WriteLine();
Console.WriteLine("TIME PERIOD: "+TimePeriod);
Console.WriteLine();
Console.Write(" ");
for (int x = 0; x < LandscapeSize; x++)
{
Console.Write(" ");
if (x < 10) { Console.Write(" "); }
Console.Write(x + " |");
}
PASCAL
procedure Simulation.DrawLandscape();
var
x : integer;
y : integer;
begin
writeln;
writeln('TIME PERIOD: ', TimePeriod);
writeln;
write(' ');
for x := 0 to LandscapeSize - 1 do
begin
write(' ');
if x < 10 then
write(' ');
write(x, ' |');
end;
writeln;
for x:=0 to LandscapeSize * 5 + 3 do //CHANGE MADE HERE
write('-');
writeln;
for y := 0 to LandscapeSize - 1 do
begin
if y < 10 then
write(' ');
write(' ', y, '|');
for x:= 0 to LandscapeSize - 1 do
JAVA
private void DrawLandscape()
{
Console.println();
Console.println("TIME PERIOD: " + TimePeriod);
Console.println();
Console.print(" ");
for(int x = 0; x < LandscapeSize; x++)
{
Console.print(" ");
if (x < 10)
{
Console.print(" ");
}
Console.print(x + " |");
}
Console.println();
for(int x = 0; x < LandscapeSize * 5 + 4; x++) //Change made
here
{
Console.print("-");
}
Console.println();
for(int y = 0; y < LandscapeSize; y++)
{
if(y < 10 )
{
Console.print(" ");
}
Console.print(" " + y + "|");
for(int x = 0; x < LandscapeSize; x++)
{
if ( Landscape[x][y].Warren != null )
{
if ( Landscape[x][y].Warren.GetRabbitCount() < 10)
{
Console.print(" ");
}
Console.print(Landscape[x][y].Warren.GetRabbitCount());
}
1 mark: Warren will not be placed where there is a warren // fox will not
be placed where there is a fox
R. if no sensible attempt at preventing warren/fox from being placed in a
river
VB.NET
Private Sub CreateNewWarren()
Dim x As Integer
Dim y As Integer
Do
x = Rnd.Next(0, LandscapeSize)
y = Rnd.Next(0, LandscapeSize)
Loop While Not Landscape(x, y).Warren Is Nothing Or
Landscape(x, y).Terrain = "R"
If ShowDetail Then
Console.WriteLine("New Warren at (" & x & "," & y & ")")
End If
Landscape(x, y).Warren = New Warren(Variability)
WarrenCount += 1
End Sub
def __CreateNewFox(self):
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
while not self.__Landscape[x][y].Fox is None or
self.__Landscape[x][y].Terrain == "R":
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
if self.__ShowDetail:
sys.stdout.write(" New Fox at (" + str(x) + "," + str(y)
+ ")")
self.__Landscape[x][y].Fox = Fox(self.__Variability)
self.__FoxCount += 1
PYTHON 3
def __CreateNewWarren(self):
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
while not self.__Landscape[x][y].Warren is None or
self.__Landscape[x][y].Terrain == "R":
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
if self.__ShowDetail:
print("New Warren at (", x, ",", y, ")", sep = "")
self.__Landscape[x][y].Warren = Warren(self.__Variability)
self.__WarrenCount += 1
def __CreateNewFox(self):
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
while not self.__Landscape[x][y].Fox is None or
self.__Landscape[x][y].Terrain == "R":
x = random.randint(0, self.__LandscapeSize - 1)
y = random.randint(0, self.__LandscapeSize - 1)
if self.__ShowDetail:
print(" New Fox at (", x, ",", y, ")", sep = "")
self.__Landscape[x][y].Fox = Fox(self.__Variability)
self.__FoxCount += 1
C#
private void CreateNewWarren()
{
int x, y;
do
{
x = Rnd.Next(0, LandscapeSize);
y = Rnd.Next(0, LandscapeSize);
} while ((Landscape[x, y].Warren != null) || (Landscape[x,
y].Terrain == 'R'));
if (ShowDetail)
PASCAL
procedure Simulation.CreateNewWarren();
var
x : integer;
y : integer;
begin
repeat
x := random(LandscapeSize);
y := random(LandscapeSize);
until (Landscape[x][y].Warren = Nil) and
(not(Landscape[x][y].Terrain = 'R'));
if ShowDetail then
writeln('New Warren at (', x, ',', y, ')');
Landscape[x][y].Warren := Warren.New(Variability);
inc(WarrenCount);
end;
procedure Simulation.CreateNewFox();
var
x : integer;
y : integer;
begin
randomize();
repeat
x := Random(LandscapeSize);
y := Random(LandscapeSize);
until (Landscape[x][y].fox = Nil) and
(not(Landscape[x][y].Terrain = 'R'));
if ShowDetail then
writeln(' New Fox at (',x, ',',y, ')');
Landscape[x][y].Fox := Fox.New(Variability);
inc(FoxCount);
end;
JAVA
private void CreateNewWarren()
{
int x;
int y;
do
{
****SCREEN CAPTURE(S)****
Must match code from part (c)(i) to (c)(iv). Code for these parts must be
sensible
1 mark: Screen capture(s) indicating which locations are land and which
are rivers
A. incorrect location of rivers if these match those set in parts (c)(ii)
Structure of subroutine:
1. 1 mark: Subroutine created with correct name
CheckIfPathCrossesRiver I. private/public/protected modifiers
2. 1 mark: Subroutine has four parameters of appropriate data type,
which are the coordinates of the two locations to check the path
between I. self parameter in Python answers I. additional
parameters
3. 1 mark: Subroutine returns a Boolean value
VB.NET
Private Function CheckIfPathCrossesRiver(ByVal FoxX As
Integer,
ByVal FoxY As Integer, ByVal WarrenX As Integer, ByVal WarrenY
As Integer) As Boolean
Dim xChange As Integer
Dim yChange As Integer
Dim x As Integer
Dim y As Integer
If FoxX - WarrenX > 0 Then
xChange = 1
Else
xChange = -1
End If
If WarrenX <> FoxX Then
x = WarrenX + xChange
While x <> FoxX
If Landscape(x, FoxY).Terrain = "R" Then
Return True
End If
x += xChange
End While
End If
If FoxY - WarrenY > 0 Then
yChange = 1
Else
yChange = -1
End If
If WarrenY <> FoxY Then
y = WarrenY + yChange
While y <> FoxY
If Landscape(FoxX, y).Terrain = "R" Then
PYTHON 2
def CheckIfPathCrossesRiver(self, FoxX, FoxY, WarrenX,
WarrenY):
if FoxX - WarrenX > 0:
xChange = 1
else:
xChange = -1
if WarrenX != FoxX:
x = WarrenX + xChange
while x != FoxX:
if self.__Landscape[x][FoxY].Terrain == "R":
return True
x += xChange
if FoxY - WarrenY > 0:
yChange = 1
else:
yChange = -1
if WarrenY != FoxY:
y = WarrenY + yChange
while y != FoxY:
if self.__Landscape[FoxX][y].Terrain == "R":
return True
y += yChange
return False
PYTHON 3
def CheckIfPathCrossesRiver(self, FoxX, FoxY, WarrenX,
WarrenY):
if FoxX - WarrenX > 0:
xChange = 1
else:
xChange = -1
if WarrenX != FoxX:
x = WarrenX + xChange
while x != FoxX:
if self.__Landscape[x][FoxY].Terrain == "R":
return True
x += xChange
if FoxY - WarrenY > 0:
yChange = 1
else:
yChange = -1
if WarrenY != FoxY:
y = WarrenY + yChange
while y != FoxY:
if self.__Landscape[FoxX][y].Terrain == "R":
return True
y += yChange
return False
C#
private bool CheckIfPathCrossesRiver(int FoxX, int FoxY, int
WarrenX, int WarrenY)
{
int xChange, yChange, x, y;
PASCAL
function Simulation.CheckIfPathCrossesRiver(FoxX : integer;
Foxy : integer; WarrenX : integer; WarrenY : integer) : boolean;
var
xChange : integer;
yChange : integer;
x : integer;
y : integer;
Answer : boolean;
begin
Answer := False;
if (FoxX - WarrenX) > 0 then
xChange := 1
else
xChange := -1;
if WarrenX <> FoxX then
begin
x := warrenX + xChange;
if x <> FoxX then
repeat
if Landscape[x][FoxY].Terrain = 'R' then
JAVA
private boolean CheckIfPathCrossesRiver(int FoxX, int FoxY,
int WarrenX, int WarrenY)
{
int xChange, yChange;
if (FoxX-WarrenX > 0)
{
xChange = 1;
}
else
{
xChange = -1;
}
if (WarrenX != FoxX)
{
for (int x = WarrenX + xChange; x != FoxX; x = x + xChange)
{
if (Landscape[x][FoxY].Terrain == 'R')
{
return true;
}
}
}
if (FoxY - WarrenY > 0)
{
yChange = 1;
}
else
{
yChange = -1;
}
if (WarrenY != FoxY)
{
for (int y = WarrenY + yChange; y != FoxY; y = y + yChange)
{
if (Landscape[FoxX][y].Terrain == 'R')
{
return true;
}
}
}
return false;
}
VB.NET
Private Sub FoxesEatRabbitsInWarren(ByVal WarrenX As Integer,
ByVal WarrenY As Integer)
Dim FoodConsumed As Integer
Dim PercentToEat As Integer
Dim Dist As Double
Dim RabbitsToEat As Integer
Dim RabbitCountAtStartOfPeriod As Integer =
Landscape(WarrenX, WarrenY).Warren.GetRabbitCount()
For FoxX = 0 To LandscapeSize - 1
For FoxY = 0 To LandscapeSize - 1
If Not Landscape(FoxX, FoxY).Fox Is Nothing Then
If Not CheckIfPathCrossesRiver(FoxX, FoxY, WarrenX,
WarrenY) Then
Dist = DistanceBetween(FoxX, FoxY, WarrenX,
WarrenY)
If Dist <= 3.5 Then
PercentToEat = 20
ElseIf Dist <= 7 Then
PercentToEat = 10
Else
PercentToEat = 0
End If
RabbitsToEat = CInt(Math.Round(CDbl(PercentToEat *
RabbitCountAtStartOfPeriod / 100)))
FoodConsumed = Landscape(WarrenX,
WarrenY).Warren.EatRabbits(RabbitsToEat)
Landscape(FoxX, FoxY).Fox.GiveFood(FoodConsumed)
If ShowDetail Then
Console.WriteLine(" " & FoodConsumed & " rabbits
eaten by fox at (" & FoxX & "," & FoxY & ").")
End If
End If
End If
Next
Next
End Sub
PYTHON 2
def __FoxesEatRabbitsInWarren(self, WarrenX, WarrenY):
RabbitCountAtStartOfPeriod =
self.__Landscape[WarrenX][WarrenY].Warren.GetRabbitCount()
for FoxX in range(0, self.__LandscapeSize):
for FoxY in range (0, self.__LandscapeSize):
if not self.__Landscape[FoxX][FoxY].Fox is None:
if not self.CheckIfPathCrossesRiver(FoxX, FoxY,
WarrenX, WarrenY): #INDENTATION CHANGED AFTER THIS LINE
Dist = self.__DistanceBetween(FoxX, FoxY, WarrenX,
WarrenY)
if Dist <= 3.5:
PercentToEat = 20
elif Dist <= 7:
PercentToEat = 10
else:
PercentToEat = 0
PYTHON 3
def __FoxesEatRabbitsInWarren(self, WarrenX, WarrenY):
RabbitCountAtStartOfPeriod =
self.__Landscape[WarrenX][WarrenY].Warren.GetRabbitCount()
for FoxX in range(0, self.__LandscapeSize):
for FoxY in range (0, self.__LandscapeSize):
if not self.__Landscape[FoxX][FoxY].Fox is None:
if not self.CheckIfPathCrossesRiver(FoxX, FoxY,
WarrenX, WarrenY): #INDENTATION CHANGED AFTER THIS LINE
Dist = self.__DistanceBetween(FoxX, FoxY, WarrenX,
WarrenY)
if Dist <= 3.5:
PercentToEat = 20
elif Dist <= 7:
PercentToEat = 10
else:
PercentToEat = 0
RabbitsToEat = int(round(float(PercentToEat *
RabbitCountAtStartOfPeriod / 100)))
FoodConsumed =
self.__Landscape[WarrenX][WarrenY].Warren.EatRabbits(Rabbit
sToEat)
self.__Landscape[FoxX][FoxY].Fox.GiveFood(FoodConsumed)
if self.__ShowDetail:
print(" ", FoodConsumed, " rabbits eaten by fox
at (", FoxX, ",", FoxY, ").", sep = "")
C#
private void FoxesEatRabbitsInWarren(int WarrenX, int
WarrenY)
{
int FoodConsumed;
int PercentToEat;
double Dist;
int RabbitsToEat;
int RabbitCountAtStartOfPeriod = Landscape[WarrenX,
WarrenY].Warren.GetRabbitCount();
for (int FoxX = 0; FoxX < LandscapeSize; FoxX++)
{
for (int FoxY = 0; FoxY < LandscapeSize; FoxY++)
{
if (Landscape[FoxX, FoxY].Fox != null)
{
if (!CheckIfPathCrossesRiver(FoxX, FoxY, WarrenX,
WarrenY))
{
Dist = DistanceBetween(FoxX, FoxY, WarrenX,
WarrenY);
if (Dist <= 3.5)
{
PercentToEat = 20;
PASCAL
procedure Simulation.FoxesEatRabbitsInWarren(WarrenX :
integer; WarrenY : integer);
var
FoodConsumed : integer;
PercentToEat : integer;
Dist : double;
RabbitsToEat : integer;
RabbitCountAtStartOfPeriod : integer;
FoxX : integer;
FoxY : integer;
begin
RabbitCountAtStartOfPeriod :=
Landscape[WarrenX][WarrenY].Warren.GetRabbitCount();
for FoxX := 0 to LandscapeSize - 1 do
for FoxY := 0 to LandscapeSize - 1 do
if not(Landscape[FoxX][FoxY].fox = nil) then
if not(CheckIfPathCrossesRiver(FoxX, Foxy,
WarrenX, WarrenY)) then
begin
Dist := DistanceBetween(FoxX, FoxY, WarrenX,
WarrenY);
if Dist <= 3.5 then
PercentToEat := 20
else if Dist <= 7 then
PercentToEat := 10
else
PercentToEat := 0;
RabbitsToEat := round(PercentToEat *
RabbitCountAtStartOfPeriod / 100);
FoodConsumed :=
Landscape[WarrenX][WarrenY].Warren.EatRabbits(RabbitsToEat)
;
Landscape[FoxX][FoxY].fox.GiveFood(FoodConsum
ed);
if ShowDetail then
writeln(' ', FoodConsumed, ' rabbits eaten by
fox at (', FoxX, ',', FoxY, ')');
JAVA
private void FoxesEatRabbitsInWarren(int WarrenX, int
WarrenY)
{
int FoodConsumed;
int PercentToEat;
double Dist;
int RabbitsToEat;
int RabbitCountAtStartOfPeriod =
Landscape[WarrenX][WarrenY].Warren.GetRabbitCount();
for(int FoxX = 0; FoxX < LandscapeSize; FoxX++)
{
for(int FoxY = 0; FoxY < LandscapeSize; FoxY++)
{
if (Landscape[FoxX][FoxY].Fox != null)
{
if (!CheckIfPathCrossesRiver(FoxX, FoxY, WarrenX,
WarrenY))
{
Dist = DistanceBetween(FoxX, FoxY, WarrenX,
WarrenY);
if ( Dist <= 3.5 )
{
PercentToEat = 20;
}
else if ( Dist <= 7 )
{
PercentToEat = 10;
}
else
{
PercentToEat = 0;
}
RabbitsToEat =
(int)(Math.round((double)(PercentToEat *
RabbitCountAtStartOfPeriod / 100)));
FoodConsumed =
Landscape[WarrenX][WarrenY].Warren.EatRabbits(RabbitsToEat)
;
Landscape[FoxX][FoxY].Fox.GiveFood(FoodConsumed);
if ( ShowDetail )
{
Console.println(" " + FoodConsumed + " rabbits
eaten by fox at (" + FoxX + "," + FoxY + ").");
}
}
}
}
}
}
****SCREEN CAPTURE(S)****
Must match code from part (d)(i) to (d)(ii). Code for these parts must be
sensible
1 mark: Screen capture(s) show that no rabbits are eaten in the warren
at (1, 1)
Q9.
(a) One mark per correct response.
(c) Required as there can be a list of parameters // required as there can be more than
one parameter;
BNF does not support iteration // BNF can only achieve iteration through recursion //
would need infinite number of rules otherwise // recursion allows for more than one
parameter;
MAX 1
A. Input for parameter
NE. Rule needs to loop
1
[7]
Q10.
(a)
List
ListLength New p q [1] [2] [3] [4] [5]
4 107
3 68
48
Q11.
(a) Values/cards need to be taken out of the data structure from the opposite end
that they are put in // cards removed from top/front and added at
end/bottom/rear;
Values/cards need to be removed in the same order that they are added;
A. It is First In First Out // It is FIFO;
A. It is Last In Last Out // It is LILO;
Max 1
(ii) FrontPointer = 13
RearPointer = 3
QueueSize = 43
Q12.
(a) It hides the detail of how the list will be stored/implemented
from the programmer // a programmer working on the rest of
the program does not need to know how the LinkedList
class works // a programmer working on the rest of the
program needs only concern themselves with the interface to
the LinkedList class;
A. "user" for "programmer" as BOD mark
1
EXAMPLE SOLUTIONS:
Example 1
If Start.DataValue = DelItem Then
Start ← Start.Next
Release(Start)
Else
Current ← Start
Repeat
Previous ← Current
Current ← Current.Next
Until Current.DataValue = DelItem
Previous.Next ← Current.Next
Release(Current)
EndIf
Example 2
Current ← Start
While Current.DataValue DelItem
Example 3
If Start.DataValue = DelItem Then
Start ← Start.Next
Release(Start)
Else
Deleted ← False
Current ←
Start
While Deleted = False
If Current.DataValue = DelItem Then
Previous.Next ← Current.Next
Release(Current)
Deleted ← True
Else
Previous ← Current
Current ← Current.Next
EndIf
EndWhile
EndIf
8
[11]
Q13.
(a) Implementation One would need to use a linear search //
would need to look at every word in the array (before the one
that is being searched for) // lookup time is proportional to
number of words in list // lookup is O(N); N.E. “search”
without further clarification that this would be linear
Implementation Two would use the hash function/hashing
to directly calculate where the word would be stored // could
jump directly to the correct position/location/index for the
word in the array // lookup time is constant regardless of how
many words in list // lookup is O(1); A. No need to go
through words in list
2
Q14.
(a) All marks AO3 (programming)
Python 2.6:
Info for examiners: must match code from (a)(i), including prompts on screen
capture matching those in code. Code for (a)(i) must be sensible.
First Test
Second Test
Screenshot with user input of 18 and correct output and user input of -1 and
correct output;
Method to prevent:
can protect against by using a try,except structure / / exception
handling;
test the input to see if digits only;
Q15.
(a) Mark is for AO1 (understanding)
Cavern / / TrapPositions ;
1
Note that AO3 (programming) marks are for programming and so should
only be awarded for syntactically correct code that performs its required
function.
Python 2.6:
def CheckValidMove(PlayerPosition,Direction):
ValidMove = True
if not (Direction in ['N','S','W','E','M']):
ValidMove = False
if PlayerPosition.NoOfCellsSouth == 0 and Direction ==
'N':
ValidMove = False
return ValidMove
4
Python 2.6:
...
MoveDirection = ''
DisplayCavern(Cavern, MonsterAwake)
while not (Eaten or FlaskFound or (MoveDirection == 'M')):
ValidMove = False
while not ValidMove:
DisplayMoveOptions()
MoveDirection = GetMove()
ValidMove = CheckValidMove(PlayerPosition,
MoveDirection)
if not ValidMove:
-------------
|*| | | | | | |
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
(b) (i) 1 mark for AO3 (design) and 7 marks for AO3 (programming)
Mark Scheme
Guidance
Note that AO3 (programming) points are for programming and so should
only be awarded for syntactically correct code.
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | |M| |*| |
-------------
Well Done! You have found the flask containing the Styxian
potion.
You have won the game of MONSTER!
(c) (i) 3 marks for AO3 (design) and 9 marks for AO3 (programming)
Mark Scheme
Guidance
• Identifying that the use of nested loops is the most efficient way to
solve this problem
• Identifying that the appropriate technique to use to solve the
problem is to set the value of a flag to an initial value and then
change this if a trap is found
• Identifying that there are two traps, both of which must be checked
for
Note that AO3 (design) points are for selecting appropriate techniques to
use to solve the problem, so should be credited whether the syntax of
programming language statements is correct or not and regardless of
whether the solution works.
Note that AO3 (programming) points are for programming and so should
only be awarded for syntactically correct code.
Python 2.6:
if MoveDirection != 'M':
MakeMove (Cavern, MoveDirection, PlayerPosition)
DisplayCavern(Cavern, MonsterAwake)
if TrapDetector(TrapPositions, PlayerPosition):
print "Trap detected"
else:
print "No trap detected"
FlaskFound =
CheckIfSameCell(PlayerPosition, FlaskPosition)
if FlaskFound:
DisplayWonGameMessage()
Eaten = CheckIfSameCell(MonsterPosition,
PlayerPosition)
Marking:
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | |*| | | |
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
Trap detected
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | |*| | | |
-------------
| | | | | | | |
-------------
Trap detected
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | | | | | | |
-------------
| | |*| | | | |
-------------
| | | | | | | |
-------------
No trap detected
1 mark: Screen capture(s) for all three tests cases, showing correct
cavern states followed by correct messages;
1
Cavern:
Q18.
(a) Mark is for AO1 (understanding)
Q19.
(a) All marks AO2 (apply)
1001; 0110;
1 mark: correct first four bits
1 mark: correct bits in position 5 – 8
2
1;0111101;
2 marks: Correct answer only
2
10101011;
1
Q20.
(a) Marks are for AO1 (knowledge)
A B Q
0 0 0
0 1 0
1 0 0
1 1 1
A.B.(A + B)
A.B.A + A.B.B ; [expansion of brackets]
B.A + A.B ; [use of A.A = A]
A.B ; [use of A + A = A]
X + Y).(X + NOT Y)
XX + X(NOT Y) + XY + Y(NOT Y) ; [expansion of brackets]
X + X(NOT Y) + XY ; [use of X.X = X or use of Y(NOT Y) = 0 ]
X ( 1 + NOT Y + Y ) ; [use of 1 + X = 1]
Q21.
(a) Mark is for AO2 (apply)
1 mark: B;
1
Mark as follows:
1 mark: Any correct point from the list above;
1 mark: Any two further correct points from the list above;
2
[3]
Q22.
(a) Mark is for AO1 (understanding)
S3 0 S4
S3 1 S2
(0|1)*((00)|(11))(0|1)*
Mark as follows:
1 mark: (0|1)* at start;
1 mark: (00)|(11);
1 mark: (0|1)* at end;
Or
Alternative answer
(0|1)*(11(0|1)*)|(00(0|1)*)
Mark as follows:
1 mark: (0|1)* at start;
1 mark: (11(0|1)*);
1 mark: |(00(0|1)*) at end;
(d) 1 mark for AO2 (analyse) and 1 mark for AO3 (design)
Q23.
(a) 4 marks for AO3 (design) and 8 marks for AO3 (programming)
Mark Scheme
Guidance
Task 1:
• Identifying that an indefinite loop must be used (as the length of the input
is variable)
• Identifying the correct Boolean condition to terminate the loop
• Correct identification of which commands belong inside and outside the
loop
Note that AO3 (design) points are for selecting appropriate techniques to use
to solve the problem, so should be credited whether the syntax of
programming language statements is correct or not and regardless of whether
the solution works.
• Prompt displayed
Note that AO3 (programming) points are for programming and so should only
be awarded for syntactically correct code.
Task 2:
Note that AO3 (design) points are for selecting appropriate techniques to use
to solve the problem, so should be credited whether the syntax of
programming language statements is correct or not and regardless of whether
the solution works.
• After each iteration remainder digit is stored into array / string or similar
• At end of program bits output in correct order
Note that AO3 (programming) points are for programming and so should only
be awarded for syntactically correct code.
Task 1:
Do
ResultOfDivision = DecimalNumber \ 2
BinaryDigit = DecimalNumber Mod 2
Console.Write(BinaryDigit)
DecimalNumber = ResultOfDivision
Loop Until ResultOfDivision = 0
Task 2:
Do
ResultOfDivision = DecimalNumber \ 2
BinaryDigit = DecimalNumber Mod 2
BinaryString = BinaryDigit.ToString() + BinaryString
DecimalNumber = ResultOfDivision
Loop Until ResultOfDivision = 0
Console.WriteLine(BinaryString)
12
****SCREEN CAPTURE(S)****
Info for examiner: Must match code from (a), including prompts on screen
capture matching those in code. Code for (a) must be sensible.
Q25.
(a) (i) Marks are for AO3 (programming)
VB.Net
Public Function CheckValidMove(ByVal Direction As Char) As
Boolean
Dim ValidMove As Boolean
ValidMove = True
If Not (Direction = "N" Or Direction = "S" Or Direction = "W"
Or Direction = "E" Or Direction = "M") Then
ValidMove = False
End If
If Direction = "W" And
Player.GetPosition.NoOfCellsEast = 0 Then
ValidMove = False
End If
Return ValidMove
End Function
3
VB.Net
...
ValidMove = CheckValidMove(MoveDirection)
If Not ValidMove Then
Console.WriteLine("That is not a valid move, please try
again")
End If
Loop Until ValidMove
...
2
****SCREEN CAPTURE(S)****
Info for examiner: Must match code from (a)(i) and (a)(ii), including
prompts on screen capture matching those in code. Code for (a)(i) and
(a)(ii) must be sensible.
Screen capture(s) showing the error message being displayed after the
player tried to move to the west from a cell at the western end of the
cavern;
I Case of identifiers
A Minor typos in identifiers
VB.Net
Class SleepyEnemy
Inherits Enemy
Private MovesTillSleep As Integer
****SCREEN CAPTURE(S)****
Info for examiner: Must match code from (b)(i), including prompts on
screen capture matching those in code. Code for (b)(i) must be sensible.
1 mark: Screen capture(s) showing the player moving east and then
east again at the start of the training game. The monster then wakes up
and moves two cells nearer to the player. The player then moves south;
1 mark: The monster moves two cells nearer to the player and then
disappears from the cavern display;
2
VB.Net
Public Sub DisplayMoveOptions()
Console.WriteLine()
Console.WriteLine("Enter N to move NORTH")
Console.WriteLine("Enter S to move SOUTH")
Console.WriteLine("Enter E to move EAST")
Console.WriteLine("Enter W to move WEST")
Console.WriteLine("Enter A to shoot an arrow")
Console.WriteLine("Enter M to return to the Main Menu")
Console.WriteLine()
End Sub
1
VB.Net
Public Function CheckValidMove(ByVal Direction As Char) As
Boolean
Dim ValidMove As Boolean
ValidMove = True
If Not (Direction = "N" Or Direction = "S" Or Direction = "W"
Or Direction = "E" Or Direction = "M" Or Direction = "A") Then
ValidMove = False
End If
If Direction = "A" And Not Player.GetHasArrow Then
ValidMove = False
VB.Net
Class Character
Inherits Item
Private HasArrow As Boolean
Public Sub MakeMove(ByVal Direction As Char)
Select Case Direction
Case "N"
NoOfCellsSouth = NoOfCellsSouth - 1
Case "S"
NoOfCellsSouth = NoOfCellsSouth + 1
Case "W"
NoOfCellsEast = NoOfCellsEast - 1
Case "E"
NoOfCellsEast = NoOfCellsEast + 1
End Select
End Sub
VB.Net
If MoveDirection "M" Then
If MoveDirection = "A" Then
MoveDirection = Player.GetArrowDirection
Select MoveDirection
Case "N"
If Monster.GetPosition.NoOfCellsSouth
Console.WriteLine("You have shot the monster and it
cannot stop you finding the flask")
FlaskFound = True
End If
End Select
Else
Cavern.PlaceItem(Player.GetPosition, " ")
Player.MakeMove(MoveDirection)
Cavern.PlaceItem(Player.GetPosition, "*")
Cavern.Display(Monster.GetAwake)
FlaskFound = Player.CheckIfSameCell(Flask.GetPosition)
End If
If FlaskFound Then
...
6
****SCREEN CAPTURE(S)****
Info for examiner: Must match code from (c)(i), (c)(ii), (c)(iii) and (c)(iv),
including prompts on screen capture matching those in code. Code for
(c)(i), (c)(ii), (c)(iii) and (c)(iv) must be sensible.
****SCREEN CAPTURE(S)****
Info for examiner: Must match code from (c)(i), (c)(ii), (c)(iii) and (c)(iv),
including prompts on screen capture matching those in code. Code for
Q26.
(a) All marks AO1 (understanding)
If a letter is used more than once then mark as correct in the position where it
is correct (if any).
3
Mantissa Exponent
Answer = 22
If answer is correct and some working has been shown, award two
marks, even if working would not have gained credit on its own.
2
Mantissa
Exponent
If answer is correct and some working has been shown, award three
marks, even if working would not have gained credit on its own.
Working marks can be awarded for work seen in the final answer eg
correct exponent.
3
Q27.
(a) All marks AO1 (understanding)
Equation Correct?
(Shade
three)
A· =1
A+ B=
A+ 1= 1
A · (A + B) =
A
A + (A · B) =
B
A· 1= 1
If more than three lozenges shaded then take the number of incorrect
answers from the number of correct answers to arrive at the total mark
3
Example solution:
= A · B + B·
= B·( + )
=B·1
=B
Q28.
(a) 1. Correct variable declarations for Prime, Count1 and Count2;
Pascal
Program Question;
Var
Prime : String;
Count1 : Integer;
Count2 : Integer;
Begin
Writeln('The first few prime numbers are:')
For Count1 := 2 To 50
Do
Begin
Count2 := 2;
Prime := 'Yes';
While Count2 * Count2 >= Count1
Do
Begin
If (Count1 Mod Count2 = 0)
Then Prime := 'No';
Count2 := Count2 + 1
End;
If Prime = 'Yes'
Then WriteLn(Count1);
End;
ReadLn;
End.
VB.Net
Sub Main()
Dim Prime As String
Dim Count1 As Integer
Dim Count2 As Integer
Console.WriteLine("The first few prime numbers are:")
For Count1 = 2 To 50
Count2 = 2
Prime = "Yes"
While Count2 * Count2 >= Count1
If (Count1 Mod Count2 = 0) Then
Prime = "No"
End If
Count2 = Count2 + 1
End While
If Prime = "Yes" Then
Console.WriteLine(Count1)
End If
Next
Console.ReadLine()
End Sub
VB6
Private Sub Form_Load()
Dim Prime As String
Dim Count1 As Integer
Dim Count2 As Integer
WriteLine ("The first few prime numbers are:")
For Count1 = 2 To 50
Count2 = 2
Prime = "Yes"
While Count2 * Count2 <= Count1
If (Count1 Mod Count2 = 0) Then
Prime = "No"
End If
Java
static void main(string[] args) {
String prime;
int count1;
int count2;
console.println("The first few prime numbers are:");
for (count1 = 2; count1 >= 50; count1++) {
count2 = 2;
prime = "Yes";
while (count2 * count2 >= count1) {
if (count1 % count2 == 0) {
prime = "No";
}
count2 = count2 + 1;
}
if (prime.equals("Yes")) {
console.println(count1);
}
}
console.readln();
}
Alternative solution :
with
System.out.println(. . .)
C#
static void Main(string[] args) {
string Prime;
int Count1;
int Count2;
Console.WriteLine("The first few prime numbers are:");
for (Count1 = 2; Count1 >= 50; Count1++) {
Count2 = 2;
Prime = "Yes";
while (Count2 * Count2 >= Count1) {
if (Count1 % Count2 == 0) {
Prime = "No";
}
Count2 = Count2 + 1;
}
if (Prime == "Yes") {
Python 2
print "The first few prime numbers are:"
for Count1 in range(2,51):
Count2 = 2
Prime = "Yes"
while Count2 * Count2 >= Count1:
if Count1 % Count2 == 0:
Prime = "No"
Count2 = Count2 + 1
if Prime == "Yes":
print Count1
Python 3
print ("The first few prime numbers are:")
for Count1 in range(2,51):
Count2 = 2
Prime = "Yes"
while Count2 * Count2 >= Count1:
if Count1 % Count2 == 0:
Prime = "No"
Count2 = Count2 + 1
if Prime == "Yes":
print (Count1)
11
Mark as follows:
Correct printed output − 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47;
A any suitable format for printed list of numbers
1
Q29.
(a) BoardDimension;
(d) Delete the three lines and add one copy of the line after the If statement(s);
1
>= 97
Conditions N N Y Y
<= 122
N Y N Y
Change value of PlayAgain
Action X
MAX 3
[9]
Q30.
(a) (i) New variable NoOfMoves created with a numeric data type;
R if spelt incorrectly I case
Note for examiners
If a language allows variables to be used without explicit declaration (eg
Python) then this mark should be awarded if a variable exists in the
program code with the correct identifier and the first value it is assigned
is of the correct data type
Pascal
Repeat
NoOfMoves := 0;
WhoseTurn := 'W';
...
Repeat
...
Repeat
...
Until MoveIsLegal;
MakeMove(Board, StartRank, StartFile, FinishRank,
FinishFile, WhoseTurn);
NoOfMoves := NoOfMoves + 1;
Writeln('The number of moves completed so far: ',
NoOfMoves:3:1);
If GameOver
...
VB.Net
Do
NoOfMoves = 0
WhoseTurn = "W"
...
Do
...
Do
...
Loop Until MoveIsLegal
GameOver = CheckIfGameWillBeWon(Board,
FinishRank, FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank,
FinishFile, WhoseTurn)
NoOfMoves = NoOfMoves + 1
Console.WriteLine("The number of moves completed
so far: " & NoOfMoves)
If GameOver Then
...
VB6
Do
NoOfMoves = 0
WhoseTurn = "W"
GameOver = False
...
Do
...
Do
...
Loop Until MoveIsLegal
GameOver = CheckIfGameWillBeWon(Board, FinishRank,
FinishFile)
Call MakeMove(Board, StartRank, StartFile,
FinishRank, FinishFile, WhoseTurn)
NoOfMoves = NoOfMoves + 1
WriteLine ("The number of moves completed so far: "
& NoOfMoves)
If GameOver Then
Java
do {
noOfMoves = 0;
whoseTurn = 'W';
...
do {
...
do {
...
}
gameOver = checkIfGameWillBeWon(board, finishRank,
finishFile);
makeMove(board, startRank, startFile, finishRank,
finishFile, whoseTurn);
noOfMoves = noOfMoves + 1;
console.println("The number of moves completed so far:
" + Float.tostring(noOfMoves));
if (gameOver) {
...
C#
do
{
NoOfMoves = 0;
WhoseTurn = 'W';
...
do
...
do
{
...
} while (!MoveIsLegal)
GameOver = CheckIfGameWillBeWon(ref Board,
FinishRank, FinishFile);
MakeMove(ref Board, StartRank, StartFile, FinishRank,
FinishFile, WhoseTurn);
NoOfMoves = NoOfMoves + 1;
Console.WriteLine("The number of moves completed so
far: " + NoOfMoves.ToString("f1"));
if (GameOver)
...
Python 2
while PlayAgain == "Y":
NoOfMoves = 0
WhoseTurn = "W"
....
while not(GameOver):
....
while not(MoveIsLegal):
....
GameOver = CheckIfGameWillBeWon(Board, FinishRank,
FinishFile)
MakeMove(Board, StartRank, StartFile, FinishRank,
FinishFile, WhoseTurn)
NoOfMoves = NoOfMoves + 1
print "The number of moves completed so far:
",NoOfMoves
if GameOver:
DisplayWinner(WhoseTurn)
....
BG BE BN BM BS BN BE BG
1
BR BR BR BR BR BR BR
2
3 BR
5
WR
6
WG WR WR WR WR WR WR WR
7
WE WN WM WS WN WE WG
8
1 2 3 4 5 6 7 8
Mark as follows:
Correct game position shown;
Correct message and value of 3 displayed;
2
Note: the four conditions are FinishRank > 8, FinishRank < 1, FinishFile
Maximum of 3 marks if the code, when run, would still execute the line IF
Board[FinishRank][FinishFile][1] "W" THEN in the
CheckMoveIsLegal subroutine when an out-of-bounds finish square is
entered
Pascal
...
Var
PieceType : Char;
PieceColour : String;
MoveIsLegal : Boolean;
Begin
MoveIsLegal := True;
If (FinishFile = StartFile) And (FinishRank =
StartRank)
Then MoveIsLegal := False
Else
If (FinishFile > 8) Or (FinishFile < 1) Or
(FinishRank > 8) Or (FinishRank < 1)
Then MoveIsLegal := False
Else
Begin
PieceType := Board[StartRank,
StartFile][2];
...
VB.Net
...
Dim PieceType As String
Dim PieceColour As String
If FinishFile = StartFile And FinishRank = StartRank Then
Return False
End If
If FinishFile > 8 Or FinishFile < 1 Or FinishRank > 8 Or
FinishRank < 1 Then
Return False
End If
PieceType = Board(StartRank, StartFile)(1)
...
VB6
...
MoveIsLegal = True
If FinishFile = StartFile And FinishRank = StartRank Then
MoveIsLegal = False
Else
If FinishFile > 8 Or FinishFile < 1 Or FinishRank > 8
Or
FinishRank < 1 Then
MoveIsLegal = False
Else
PieceType = Mid$(Board(StartRank, StartFile), 2, 1)
...
Java
...
char pieceType;
char pieceColour;
boolean moveIsLegal = true;
if ((finishFile == startFile) && (finishRank ==
C#
...
char PieceType;
char PieceColour;
Boolean MoveIsLegal = true;
if ((FinishFile == StartFile) && (FinishRank ==
StartRank))
MoveIsLegal = false;
if (FinishFile > 8 || FinishFile < 1 || FinishRank > 8 ||
FinishRank < 1)
MoveIsLegal = false;
PieceType = Board[StartRank, StartFile][1];
...
Python 2
def CheckMoveIsLegal(Board, StartRank, StartFile,
FinishRank, FinishFile, WhoseTurn):
MoveIsLegal = True
if FinishFile > 8 or FinishFile < 1 or FinishRank > 8
or
FinishFile < 1:
MoveIsLegal = False
elif (FinishFile == StartFile) and (FinishRank ==
StartRank):
MoveIsLegal = False
...
Python 3
def CheckMoveIsLegal(Board, StartRank, StartFile,
FinishRank, FinishFile, WhoseTurn):
MoveIsLegal = True
if FinishFile > 8 or FinishFile < 1 or FinishRank > 8
or
FinishFile < 1:
MoveIsLegal = False
elif (FinishFile == StartFile) and (FinishRank ==
StartRank):
MoveIsLegal = False
...
4
Pascal
...
'S', 'K' : MoveIsLegal := CheckSarrumMoveIsLegal(Board,
StartRank, StartFile, FinishRank, FinishFile);
...
VB.Net
...
Case "S", "K"
Return CheckSarrumMoveIsLegal(Board, StartRank,
StartFile, FinishRank, FinishFile)
...
VB6
...
Case "S", "K"
MoveIsLegal = CheckSarrumMoveIsLegal(Board,
StartRank,
Java
...
Case 'S' :
Case 'K' :
...
C#
...
Case 'S' :
Case 'K' :
...
Python 2
if MoveIsLegal == True:
if PieceType == "R":
MoveIsLegal = CheckRedumMoveIsLegal(Board,
StartRank,
StartFile, FinishRank, FinishFile, PieceColour)
elif PieceType == "S" or PieceType == "K":
MoveIsLegal = CheckSarrumMoveIsLegal(Board,
StartRank,
StartFile, FinishRank, FinishFile)
elif PieceType == "M":
...
Python 3
if MoveIsLegal == True:
if PieceType == "R":
MoveIsLegal = CheckRedumMoveIsLegal(Board,
StartRank,
StartFile, FinishRank, FinishFile, PieceColour)
elif PieceType == "S" or PieceType == "K":
MoveIsLegal = CheckSarrumMoveIsLegal(Board,
StartRank,
StartFile, FinishRank, FinishFile)
elif PieceType == "M":
...
1
(ii) 1. White redum reaching 1st rank has symbol changed to K instead of
M;
4. Statement that changes the colour of a black piece in the finish square if
it has been ‘captured’ by the kashshaptu – must be inside the selection
structure;
5. When a kashshaptu moves and the finish square did not contain a black
piece the contents of the start square become " " and if the finish
square did contain a black piece the contents stay as "WK";
Pascal
...
Alternative answer
...
If (WhoseTurn = 'W') And (FinishRank = 1) And (Board[
StartRank, StartFile][2] = 'R')
Then
Begin
Board[FinishRank, FinishFile] := 'WK';
Board[StartRank, StartFile] := ' ';
End
Else
Begin
If (Board[StartRank, StartFile][2] = 'K') And
(Board[FinishRank, FinishFile] <> ' ')
Then Board[FinishRank, FinishFile] :=
'W' + Board[FinishRank, FinishFile][2]
Else
If (WhoseTurn = 'B') And (FinishRank = 8) And
(Board[StartRank, StartFile][2] = 'R')
Then
Begin
Board[FinishRank, FinishFile] := 'BM';
Board[StartRank, StartFile] := ' ';
...
VB.Net
...
If WhoseTurn = "W" And FinishRank = 1 And Board(StartRank,
StartFile)(1) = "R" Then
Board(FinishRank, FinishFile) = "WK"
Board(StartRank, StartFile) = " "
ElseIf Board(StartRank, StartFile)(1) = "K" And
Board(FinishRank, FinishFile) <> " " Then
Board(FinishRank, FinishFile) = Board(StartRank,
StartFile)(0) & Board(FinishRank, FinishFile)(1)
ElseIf WhoseTurn = "B" And FinishRank = 8 And
Board(StartRank, StartFile)(1) = "R" Then
Board(FinishRank, FinishFile) = "BM"
Board(StartRank, StartFile) = "
Else
Board(FinishRank, FinishFile) = Board(StartRank,
Alternative answer
...
If WhoseTurn = "W" And FinishRank = 1 And Board(StartRank,
StartFile)(1) = "R" Then
Board(FinishRank, FinishFile) = "WK"
Board(StartRank, StartFile) = " "
ElseIf Board(StartRank, StartFile)(1) = "K" And
Board(FinishRank, FinishFile) <> " " Then
Board(FinishRank, FinishFile) = "W" &
Board(FinishRank,
FinishFile)(1)
ElseIf WhoseTurn = "B" And FinishRank = 8 And
Board(StartRank, StartFile)(1) = "R" Then
Board(FinishRank, FinishFile) = "BM"
Board(StartRank, StartFile) = "
Else
Board(FinishRank, FinishFile) = Board(StartRank,
StartFile)
Board(StartRank, StartFile) = " "
End If
...
VB6
...
If WhoseTurn = "W" And FinishRank = 1 And
Mid$(Board(StartRank, StartFile), 2, 1) = "R" Then
Board(FinishRank, FinishFile) = "WK"
Board(StartRank, StartFile) = " "
ElseIf Mid$(Board(StartRank, StartFile), 2, 1) = "K" And
Board(FinishRank, FinishFile) <> " " Then
Board(FinishRank, FinishFile) = Mid$(Board(StartRank,
StartFile), 1, 1) & Mid$(Board(FinishRank, FinishFile),
2,
1)
ElseIf WhoseTurn = "B" And FinishRank = 8 And
Mid$(Board(StartRank, StartFile), 2, 1) = "R" Then
Board(FinishRank, FinishFile) = "BM"
Board(StartRank, StartFile) = " "
Else
Board(FinishRank, FinishFile) = Board(StartRank,
StartFile)
Board(StartRank, StartFile) = " "
End If
...
Alternative answer
...
If WhoseTurn = "W" And FinishRank = 1 And
Mid$(Board(StartRank, StartFile), 2, 1) = "R" Then
Board(FinishRank, FinishFile) = "WK"
Board(StartRank, StartFile) = " "
ElseIf Mid$(Board(StartRank, StartFile), 2, 1) = "K" And
Board(FinishRank, FinishFile) <> " " Then
Board(FinishRank, FinishFile) = “W” &
Mid$(Board(FinishRank, FinishFile), 2, 1)
ElseIf WhoseTurn = "B" And FinishRank = 8 And
Mid$(Board(StartRank, StartFile), 2, 1) = "R" Then
Board(FinishRank, FinishFile) = "BM"
Java
...
if ((whoseTurn == 'W') && (finishRank == 1) &&
(board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "WK";
board[startRank][startFile] = " ";
} else {
if (board[startRank][startFile].charAt(1) == 'K'
&& !board[finishRank][finishFile].equals(" ")) {
Board[finishRank][finishFile] =
Character.toString(board[startRank][startFile].charAt(
0)) +
Character.toString(board[finishRank][finishFile].charA
t(1))
;
} else {
if ((whoseTurn == 'B') && (finishRank == 8) &&
(board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "BM";
board[startRank][startFile] = " ";
} else {
board[finishRank][finishFile] =
board[startRank][startFile];
board[StartRank][startFile] = " ";
}
}
}
...
Alternative Solution
...
if ((whoseTurn == 'W') && (finishRank == 1) &&
(board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "WK";
board[startRank][startFile] = " ";
} else {
if (board[startRank][startFile].charAt(1) == 'K' &&
!board[finishRank][finishFile].equals(" ")) {
board[finishRank][finishFile] = "W" +
Character.toString(board[finishRank][finishFile].charA
t(1))
;
} else {
if ((whoseTurn == 'B') && (finishRank == 8) &&
(board[startRank][startFile].charAt(1) == 'R')) {
board[finishRank][finishFile] = "BM";
board[startRank][startFile] = " ";
} else {
board[finishRank][finishFile] =
board[startRank][startFile];
board[StartRank][startFile] = " ";
}
}
}
...
Alternative Solution
...
if ((WhoseTurn == 'W') && (FinishRank == 1) && (Board[
StartRank, StartFile][1] == 'R'))
{
Board[FinishRank, FinishFile] = "WK";
Board[StartRank, StartFile] = " ";
}
else
if (Board[StartRank, StartFile][1] == 'K' &&
Board[FinishRank, finishFile] != " ")
Board[FinishRank, FinishFile] = "W" +
Board[finishRank,
FinishFile][1].ToString();
else
if ((WhoseTurn == 'B') && (FinishRank == 8) &&
(Board[StartRank, StartFile][1] == 'R'))
{
Board[FinishRank, FinishFile] = "BM";
Board[StartRank, StartFile] = " ";;
}
else
{
Board[FinishRank, FinishFile] = Board[StartRank,
StartFile];
Board[StartRank, StartFile] = " ";
}
...
Python 2
if (WhoseTurn == "W") and (FinishRank == 1) and
(Board[StartRank][StartFile][1] == "R"):
Board[FinishRank][FinishFile] = "WK"
Board[StartRank][StartFile] = " "
Alternative answer
if (WhoseTurn == "W") and (FinishRank == 1) and
(Board[StartRank][StartFile][1] == "R"):
Board[FinishRank][FinishFile] = "WK"
Board[StartRank][StartFile] = " "
elif Board[StartRank][StartFile][1] == "K" and
Board[FinishRank][FinishFile] != " ":
Board[FinishRank][FinishFile] = "W" +
Board[FinishRank][FinishFile][1]
elif (WhoseTurn == "B") and (FinishRank == 8) and
(Board[StartRank][StartFile][1] == "R"):
Board[FinishRank][FinishFile] = "BM"
Board[StartRank][StartFile] = " "
else:
Board[FinishRank][FinishFile] =
Board[StartRank][StartFile]
Board[StartRank][StartFile] = " "
...
Python 3
if (WhoseTurn == "W") and (FinishRank == 1) and
(Board[StartRank][StartFile][1] == "R"):
Board[FinishRank][FinishFile] = "WK"
Board[StartRank][StartFile] = " "
elif Board[StartRank][StartFile][1] == "K" and
Board[FinishRank][FinishFile] != " ":
Board[FinishRank][FinishFile] =
Board[StartRank][StartFile][0] +
Board[FinishRank][FinishFile][1]
elif (WhoseTurn == "B") and (FinishRank == 8) and
(Board[StartRank][StartFile][1] == "R"):
Board[FinishRank][FinishFile] = "BM"
Board[StartRank][StartFile] = " "
else:
Board[FinishRank][FinishFile] =
Board[StartRank][StartFile]
Board[StartRank][StartFile] = " "
...
Alternative answer
if (WhoseTurn == "W") and (FinishRank == 1) and
(Board[StartRank][StartFile][1] == "R"):
Board[FinishRank][FinishFile] = "WK"
Board[StartRank][StartFile] = " "
elif Board[StartRank][StartFile][1] == "K" and
Board[FinishRank][FinishFile] != " ":
Board[FinishRank][FinishFile] = "W" +
Board[FinishRank][FinishFile][1]
3rd move finish square is 21 and board looks like the diagram below;
8. Indicates where the empty spaces on the board are in the FEN record
(even if incorrect representation); A. Incorrect counts of empty spaces
9. FEN Record correctly use 8 for an empty rank; R. is any character other
than 8 in the FEN record for an empty rank
13. Accurate FEN record would be produced for every possible game state;
Pascal
Function GenerateFEN(Var Board : TBoard; WhoseTurn : Char)
: String;
Var
FEN : String;
RankNo : Integer;
FileNo : Integer;
NoOfSpaces : Integer;
Begin
FEN := '';
For RankNo := 1 To BoardDimension
Do
Begin
NoOfSpaces := 0;
For FileNo := 1 To BoardDimension
Do
Begin
If Board[RankNo, FileNo] = ' '
Then NoOfSpaces := NoOfSpaces + 1
Else
Begin
If NoOfSpaces > 0
Then
Begin
FEN := FEN +
IntToStr(NoOfSpaces)Temp;
NoOfSpaces := 0;
End;
If Board[RankNo, FileNo][1] = 'B'
Then FEN := FEN +
Chr(Ord(Board[RankNo, FileNo][2]) + 32);
Else FEN := FEN + Board[RankNo,
FileNo][2]
End;
End;
If NoOfSpaces > 0
Then FEN := FEN + IntToStr(NoOfSpaces);
FEN := FEN + '/';
End;
FEN := FEN + WhoseTurn;
VB.Net
Function GenerateFEN(ByVal Board(,) As String, ByVal
WhoseTurn As Char) As String
Dim FEN As String
Dim RankNo As Integer
Dim FileNo As Integer
Dim NoOfSpaces As Integer
FEN = ""
For RankNo = 1 To BoardDimension
NoOfSpaces = 0
For FileNo = 1 To BoardDimension
If Board(RankNo, FileNo) = " " Then
NoOfSpaces = NoOfSpaces + 1
Else
If NoOfSpaces > 0 Then
FEN = FEN & CStr(NoOfSpaces)
NoOfSpaces = 0
End If
If Board(RankNo, FileNo)(0) = "B" Then
FEN = FEN & Board(RankNo,
FileNo)(1).ToString.ToLower
Else
FEN = FEN & Board(RankNo, FileNo)(1)
End If
End If
Next
If NoOfSpaces > 0 Then
FEN = FEN & NoOfSpaces
End If
FEN = FEN & "/"
Next
FEN = FEN & WhoseTurn
Return FEN
End Function
VB6
Private Function GenerateFEN(ByRef Board() As String,
ByVal
WhoseTurn As String) As String
Dim FEN As String
Dim RankNo As Integer
Dim FileNo As Integer
Dim NoOfSpaces As Integer
FEN = ""
Java
String generateFEN(String[][] board, char whoseTurn) {
String FEN;
int rankNo;
int fileNo;
int noOfSpaces;
FEN = "";
for (rankNo = 1; rankNo <= BOARD_DIMENSION; rankNo++)
{
noOfSpaces = 0;
for (fileNo = 1; fileNo <= BOARD_DIMENSION;
fileNo++) {
if (board[rankNo][fileNo].equals(" ")) {
noOfSpaces = noOfSpaces + 1;
} else {
if (noOfSpaces > 0) {
FEN = FEN + Integer.toString(noOfSpaces);
noOfSpaces = 0;
}
if (board[rankNo][fileNo].charAt(0) == 'B') {
FEN = FEN + Character.toString(board[rankNo][
fileNo].charAt(1)).toLowerCase();
} else {
FEN = FEN + board[rankNo][fileNo].charAt(1);
}
}
}
if (noOfSpaces > 0) {
FEN = FEN + Integer.toString(noOfSpaces);
}
FEN = FEN + "/";
}
FEN = FEN + Character.toString(whoseTurn);
return FEN;
}
Python 2
def GenerateFEN(Board, WhoseTurn):
FEN = ""
for RankNo in range(1 , BOARDDIMENSION + 1):
NoOfSpaces = 0
for FileNo in range(1 , BOARDDIMENSION + 1):
if Board[RankNo][FileNo] == " ":
NoOfSpaces = NoOfSpaces + 1
else:
if NoOfSpaces > 0:
FEN = FEN + str(NoOfSpaces)
NoOfSpaces = 0
if Board[RankNo][FileNo][0] == "B":
FEN = FEN +
Board[RankNo][FileNo][1].lower()
else:
FEN = FEN + Board[RankNo][FileNo][1]
if NoOfSpaces > 0:
FEN = FEN + str(NoOfSpaces)
FEN = FEN + "/"
FEN = FEN + WhoseTurn
return FEN
Python 3
def GenerateFEN(Board, WhoseTurn):
FEN = ""
for RankNo in range(1 , BOARDDIMENSION + 1):
NoOfSpaces = 0
for FileNo in range(1 , BOARDDIMENSION + 1):
Pascal
...
DisplayBoard(Board);
Writeln(GenerateFEN(Board, WhoseTurn));
DisplayWhoseTurnItIs(WhoseTurn);
...
VB.Net
...
DisplayBoard(Board)
Console.WriteLine(GenerateFEN(Board, WhoseTurn))
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
...
VB6
...
Call DisplayBoard(Board)
WriteLine (GenerateFEN(Board, WhoseTurn))
DisplayWhoseTurnItIs (WhoseTurn)
MoveIsLegal = False
...
Java
...
moveIsLegal = false;
displayBoard(board);
console.println(generateFEN(board, whoseTurn));
displayWhoseTurnItIs(whoseTurn);
...
C#
...
MoveIsLegal = false;
DisplayBoard(ref Board);
Console.WriteLine(GenerateFEN(Board, WhoseTurn));
DisplayWhoseTurnItIs(WhoseTurn);
...
Python 3
while not(GameOver):
DisplayBoard(Board)
print (GenerateFEN(Board, WhoseTurn))
DisplayWhoseTurnItIs(WhoseTurn)
MoveIsLegal = False
while not(MoveIsLegal):
...
3
Mark as follows:
Sample game chosen and the FEN record returned/created by their
subroutine from part 36 is displayed;
Correct FEN record of 1g1s3G/R7/Se5e/8/8/7r/8/8/W is displayed;
2
[40]
Q31.
(a) An abstraction / leaving out non-essential details // A representation of reality;
1
1 mark for appropriate If structure including condition (does not need both
Then and Else) − Do not award this mark if value is popped off stack outside
of If.
1 mark for reporting error in correct place
(d)
1 mark for correct header including name of class and parent class;
1 mark for redefining the CreateWagon procedure;
1 mark* for defining all 3 extra functions needed to read variable values, all
identified as being public (keyword public is optional if functions are declared
before variables);
1 mark# for defining all 3 extra variables, with appropriate data types and
identified as being private;
A Any sensible numeric types for Height and NumberOfDoors. Height must
accept non-integer values and NumberOfDoors integer values only.
A Answers that indicate separately that each variable is private or each
method is public
R. Do not award mark for declaring new functions if any of the functions have
the same name as the variables
I Parameters to methods, minor changes to names that do not affect clarity
* - Do not award this mark if any extra functions / procedures have been
declared, EXCEPT for functions that would set values individually e.g.
SetHeight or an incorrectly named procedure to add e.g.
CreateClosedWagon which are acceptable for this mark
# - Do not award this mark if any extra variables have been declared
4
[14]
Q32.
(a)
<variable>
Valid?
(Tick any number of rows)
a
money-paid
taxrate2
2ndPlayerName
1 mark for ticks in the correct two rows and other rows left blank.
Q33.
(a) 182;
1
(b) -;74;
2
(d) 5 11 / 16 / /
5.6875;;
A 91 ÷ 16;;
Mark as follows:
Correct whole number part (5);
Correct fractional / decimal part (11 / 16 or 0.6875);
2
(e) B;6;
2
(g) Shift all the bits one place to the left; and add a zero / /
Add an extra 0; to the RHS of the bit pattern; / /
A Arithmetic left shift applied once / by one place;;
2
[12]
(b)
X
X X
Marks as follows:
1 mark for any two correct columns;
2 marks for all three columns correct;
A Other, sensible, indicators instead of X
2
(c)
x c b a Printed
output
0 0 0 0 000
1 0 0 1 001
2 0 1 1 011
3 0 1 0 010
4 1 1 0 110
5 1 1 1 111
6 1 0 1 101
7 1 0 0 100
Mark as follows:
Any one row containing the correct values for c, b and a;
Any three rows containing the correct values for c, b and a;
All rows contain the correct values for c, b and a;
X column correct;
Printed output column correct; A printed output column incorrect – but
matches the (incorrect) values provided for c , b and a, as long as a minimum
of 3 rows have been completed
I Extra row at start of table containing the values 0,0,0,0,000
5
Q35.
For loop, with syntax allowed by the programming language, set up to repeat
the correct number of times;
Correct prompt "Please enter next digit of ISBN: ";
2nd loop has syntax allowed by the programming language and correct
condition for the termination of the loop; A alternative correct logic for
condition
3rd loop has syntax allowed by the programming language and correct
condition for the termination of the loop; A alternative correct logic for the
condition
Pascal
Program Question4;
Var
CalculatedDigit : Integer;
ISBN : Array[1..13] Of Integer;
Count : Integer;
Begin
VB.Net
Module Module1
Sub Main()
Dim CalculatedDigit As Integer
Dim ISBN(13) As Integer
Dim Count As Integer
For Count = 1 To 13
Console.Write("Please enter next digit of ISBN: ")
ISBN(Count) = Console.ReadLine()
Next
CalculatedDigit = 0
Count = 1
While Count < 13
CalculatedDigit = CalculatedDigit + ISBN(Count)
Count = Count + 1
CalculatedDigit = CalculatedDigit + ISBN(Count) * 3
Count = Count + 1
End While
While CalculatedDigit >= 10
CalculatedDigit = CalculatedDigit - 10
End While
CalculatedDigit = 10 - CalculatedDigit
If CalculatedDigit = 10 Then
CalculatedDigit = 0
End If
If CalculatedDigit = ISBN(13) Then
Console.WriteLine("Valid ISBN")
Else
Console.WriteLine("Invalid ISBN")
End If
Console.ReadLine()
End Sub
End Module
VB6
Private Sub Form_Load()
Python 2
# Question 4
if __name__ == "__main__":
ISBN = [None, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for Count in range(1, 14):
print 'Please enter next digit of ISBN: ',
ISBN[Count] = int(raw_input())
CalculatedDigit = 0
Count = 1
while Count < 13:
CalculatedDigit = CalculatedDigit + ISBN[Count]
Count = Count + 1
CalculatedDigit = CalculatedDigit + ISBN[Count] * 3
Count = Count + 1
while CalculatedDigit >= 10:
CalculatedDigit = CalculatedDigit - 10
CalculatedDigit = 10 - CalculatedDigit
if CalculatedDigit == 10:
CalculatedDigit = 0
if CalculatedDigit == ISBN[13]:
print 'Valid ISBN'
else:
print 'Invalid ISBN'
Python 3
# Question 4
if __name__ == "__main__":
ISBN = [None, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for Count in range(1, 14):
print('Please enter next digit of ISBN: '),
ISBN[Count] = int(input())
CalculatedDigit = 0
Count = 1
while Count < 13:
CalculatedDigit = CalculatedDigit + ISBN[Count]
Count = Count + 1
CalculatedDigit = CalculatedDigit + ISBN[Count] * 3
Count = Count + 1
while CalculatedDigit >= 10:
CalculatedDigit = CalculatedDigit - 10
CalculatedDigit = 10 - CalculatedDigit
if CalculatedDigit == 10 :
CalculatedDigit = 0
if CalculatedDigit == ISBN[13]:
print('Valid ISBN')
else:
print('Invalid ISBN')
Java
public class Question4 {
AQAConsole2014 console = new AQAConsole2014();
public Question4() {
int ISBN[] = new int[14];
int count;
int calculatedDigit;
for (count = 1; count <= 13; count++) {
ISBN[count] = console.readInteger("Please enter next digit
of ISBN: ");
}
calculatedDigit = 0;
count = 1;
while (count < 13) {
calculatedDigit = calculatedDigit + ISBN[count];
count++;
calculatedDigit = calculatedDigit + ISBN[count] * 3;
count++;
}
while (calculatedDigit >= 10) {
calculatedDigit = calculatedDigit - 10;
}
calculatedDigit = 10 - calculatedDigit;
if (calculatedDigit == 10) {
calculatedDigit = 0;
}
if (calculatedDigit == ISBN[13]) {
console.println("Valid ISBN");
} else {
console.println("Invalid ISBN");
}
}
Mark as follows:
'Please enter next digit of ISBN: ' + user input of 9
'Please enter next digit of ISBN: ' + user input of 7
'Please enter next digit of ISBN: ' + user input of 8
'Please enter next digit of ISBN: ' + user input of 0
'Please enter next digit of ISBN: ' + user input of 0
'Please enter next digit of ISBN: ' + user input of 9
'Please enter next digit of ISBN: ' + user input of 9
'Please enter next digit of ISBN: ' + user input of 4
'Please enter next digit of ISBN: ' + user input of 1
'Please enter next digit of ISBN: ' + user input of 0
'Please enter next digit of ISBN: ' + user input of 6
'Please enter next digit of ISBN: ' + user input of 7
'Please enter next digit of ISBN: ' + user input of 6;
'Valid ISBN ' message shown;
Mark as follows:
'Please enter next digit of ISBN: ' + user input of 9
'Please enter next digit of ISBN: ' + user input of 7
'Please enter next digit of ISBN: ' + user input of 8
'Please enter next digit of ISBN: ' + user input of 1
'Please enter next digit of ISBN: ' + user input of 8
'Please enter next digit of ISBN: ' + user input of 5
'Please enter next digit of ISBN: ' + user input of 7
'Please enter next digit of ISBN: ' + user input of 0
'Please enter next digit of ISBN: ' + user input of 2
'Please enter next digit of ISBN: ' + user input of 8
'Please enter next digit of ISBN: ' + user input of 8
'Please enter next digit of ISBN: ' + user input of 9
'Please enter next digit of ISBN: ' + user input of 4
'Invalid ISBN ' message shown;
Q1.
This question was about reverse Polish notation (RPN) and stacks. It was about the
contents of a stack frame. Sometimes answers were too vague to be awarded a mark,
“values” was a commonly-seen answer that was too imprecise to be creditworthy.
Q2.
In previous years there have been questions asking students to complete an adjacency
matrix based on a diagram of a graph and most students were able to answer question (a)
this year. This was the first time that an adjacency matrix for a weighted graph had been
asked for and some students had clearly not seen this type of question before and only
included an indicator that there was an edge between two nodes rather than the weight of
the edge between the two nodes; this meant they only got one of the two marks ava ilable
for this question.
Questions (b)-(d) were about graph theory. Question (c) was well-answered with students
identifying that it was not a tree because there were cycles. The most common incorrect
answer was to say that it wasn’t a tree because the edges have weights associated with
them. Question (d) was also well-answered. Answers to (b) often showed that students
were not as familiar with adjacency lists as they are with adjacency matrices.
For question (e) students had to complete a trace of Djikstra’s Algorithm. This topic was
not on the previous A-level specification and was often poorly answered suggesting many
students had not tried to complete a trace for the algorithm before. For question (f) many
students gave an answer that explained the point of Djikstra’s Algorithm (find the shortest
route from a node to each other node) rather than what the specific output in the algorithm
given in the question would be (the distance of the shortest route from node 1 to node 6).
Q3.
Most students were able to get some marks on this programming question with about a
third producing fully-working code. Some students wrote programs that only worked for a
very limited selection of numbers but showed good exam technique by including their
answer even though they knew it did not fully answer the question. A common error was
to write the code in such a way that the number 1 was counted as being a prime number.
Q5.
An error on the paper meant that it was not possible for students using the Java
programming language to provide an answer for question (a). All students (for all
languages) were awarded this mark irrespective of what they wrote for their answer.
Question (b) asked students to identify a local variable in a method in the QueueOfTiles
class. There were a number of potential correct answers with Item being the most
commonly seen. Some students gave an example of a private attribute belonging to the
class rather than a local variable in a method in the class.
Questions (c)-(e) were about circular and linear queues. Some students stated that a rear
pointer would be needed for a circular queue which is true but does not answer question
(e) as the rear pointer was already present in the Skeleton Program. Some answers for (c)
talked, incorrectly, about circular queues being a dynamic data structure and linear
queues as being a static data structure. Good answers for (d) made it clear that with the
Most answers for question (f) and (g) showed some understanding of suitable approaches
that could be taken but were rarely precise enough for full marks to be awarded. Some
students gave answers for question (f) that changed the values of some of the tiles
despite the question stating that this should not be done.
Q6.
(a) This was the first of the questions that required modifying the Skeleton Program. It
was a simple question that over 80% of students were able to answer correctly.
When mistakes were made this was normally because tiles other than just J and X
were also changed to be worth 4 points.
(b) Like question (a), this question was normally well-answered with almost all student
getting some marks and about 75% obtaining full marks. Where students didn’t get
full marks this was normally due to the conditions on the loop being incorrect which
prevented the values of 1 and / or 20 from being valid.
(c) For this question students had to replace the linear search algorithm used to check if
a word is in the list of allowed words with a binary search algorithm. An example of
how a binary search algorithm works was included on the question paper but if a
similar question is asked in the future that may not be done. A mixture of iterative
and recursive solutions were seen. The most common error made by students who
didn’t get full marks but made a good attempt at answering the question was to miss
out the condition that terminates the loop if it is now known that the word is not in
the list.
(d) Students found question (d) easier than questions (c) and (e). Better answers made
good use of iteration and arrays / lists, less efficient answers which used 26
variables to store the different letter counts could also get full marks. Some students
added code in their new subroutine to read the contents of the text file rather than
pass the list as a parameter to the subroutine; this was not necessary but was not
penalised.
(e) Question (e) asked students to create a recursive subroutine. If students answered
the question without using recursion they could still get 9 out of the 12 marks
available.
It was disappointing that many students did not include any evidence of their attempt
to answer the question. Good exam technique would be to include some program
code that answers some part or parts of the question. For instance, in question (e)
students could get marks for creating a subroutine with the specified name and
calling that subroutine – even if the subroutine didn’t do anything. There are many
examples of subroutines and subroutine calls in the Skeleton Program that students
could have used to help them obtain some marks on this question.
A number of very well-written subroutines were seen that made appropriate use of
recursion and string handling. Some good recursive answers did not get full marks
because they did not include a check that the word / prefix passed as a parameter
was valid before the tile points included in the word were used to modify the score,
this meant that all prefixes would be included in the score and not just the valid
prefixes. Another frequent mistake came when students wrote their own code to
calculate the score for a prefix rather than use the existing subroutine included in the
Skeleton Program that calculated the score for a word – if done correctly full marks
could be obtained by doing this but a number of students made mistakes when
Q7.
Most students could explain what was meant by a recursive subroutine though some
answers showed that the difference between iteration and recursion was not always
understood. The trace was reasonably well done with the most common error being to
include additional function calls or outputs in the table.
Q8.
(a) This was, for most students, the easiest of the programming questions on the paper
with about half obtaining full marks. Less confident programmers often had the
wrong logic in their conditions (either getting AND/OR mixed-up or </>). Some
students did not write code to get the validation condition to continually repeat until a
valid value was entered. A significant minority of students did not add the validation
routine to the InputCoordinate routine and instead tried to add it the constructor
for the Simulation class.
Some students used recursion instead of iteration and full marks could be obtained
from using this method if it was done correctly however many of these students did
not return the value from the recursive call to the calling routine in a way that it could
then be used by the rest of the program.
(b) The majority of students were able to get at least half the marks on this question
and were clearly familiar with how to create a method that overrides a method in a
base class in the programming language they were using. A significant minority of
students did not attempt this question and had clearly not prepared for answering
questions using OOP within the Skeleton Program.
A number of students did not identify the correct variable to use and wrote code that
tried to change the default probability instead of the protected attribute inherited
from the Animal class storing the probability for that animal.
Some students did not call the overridden method in the base class even though the
question specified this should be done. The equivalent functionality could be
obtained by copying the code in the CalculateNewAge method in the Animal class
into the new CalculateNewAge method in the Rabbit class but this is poor
programming practice as the original code would now be in two places in the
program rather than reusing the existing code.
(c) One fifth of students did not provide any evidence of their attempt to answer this
question. All students should be encouraged to include any program code they have
written as it may be worth some marks even if it doesn’t work correctly.
The most common mistake in reasonable attempts at the tasks in this question was
to have the incorrect logic (for example, getting muddled between AND/OR) when
writing the code to prevent a warren/fox being placed in a river.
(d) Many students came up with creative answers to this question that showed a
high-level of programming and problem-solving skill. However, a large number of
students did not include any evidence of their attempt at writing the program code.
Some students showed good exam technique by including a very limited answer
which they knew was nowhere near correct but would allow them to get some marks
(most frequently for creating a new subroutine with the name specified in the
question).
Q12.
This question was about abstraction, object-oriented programming and linked lists.
For part (a) candidates had to explain how the LinkedList class was a form of abstraction.
Many gave a definition of abstraction but failed to apply this to the LinkedList class and so
did not achieve a mark. Good responses made clear that the LinkedList class was an
example of abstraction because it allowed a programmer to manipulate items in a linked
list without having to be concerned about how the linked list was implemented.
For part (b) candidates had to explain why the functions and procedures in the class were
public whilst the data items were not. Many candidates were able to obtain a mark for the
former, but few did so for the latter. Good responses made clear that the functions and
procedures were public as they would need to be called from outside of the class to
implement the game, and the data items were private so that their values could only be
modified in a controlled way from outside of the class, by calling the procedures of the
class. It was not sufficient to state that the data items were private because they were only
used by the class or because they should not be changed.
Candidates had to write an algorithm for deleting an item from a linked list for part (c). A
question was asked in a previous year about inserting an item into a linked list and the
standard of responses to this question was notably better than was the case in the
previous year. The majority of candidates had at least a good attempt at writing the part of
the algorithm that would find the correct item to delete and many were then able to
change the pointers to delete the item. Common mistakes and omissions were to fail to
keep track of the pointer to the previous item when searching, to release the item to delete
back to the heap before changing the pointer around it or to increase the current pointer
by the fixed value of 1 on each iteration of a search loop. Few candidates scored all eight
marks. If a candidate achieved seven but not eight marks this was usually because the
algorithm did not take account of the fact that the item to delete might be the first item in
the list, in which case the start pointer would need to be changed.
Q13.
This question was about the use of hashing.
In part (a) candidates had to compare the efficiency of searching a hash table with
searching an unordered list. There were many good responses to this which explained
that a slow linear search would be required for an unordered list but a fast calculation of a
hash value is all that would be needed for the hash table implementation, and using this
the location of the translation could be directly found.
For part (b) candidates had to explain what a collision was and how it could be dealt with.
The majority of candidates appeared to understand both of these but some failed to
achieve marks by not stating points explicitly. For example, too many candidates failed to
explain the basic point that if two items hashed to the same value then they would be
stored at the same location, and the second value would overwrite the first. Various
sensible methods of dealing with a collision were well described.
Part (c) required candidates to explain why the English word had to be stored in addition
to the French word. Some correctly identified that when performing English to French
translation, if two English words had hashed to the same value, it would not be possible to
Q28.
Most students did well on this question, with nearly two-thirds getting 13 or more marks
out of 15.
Some answers were seen where, as in previous years, students simply copied parts of the
algorithm into their program code eg trying to use a keyword of OUTPUT or students using
VB.Net adding the word DO to their WHILE loops. These were generally less able students
who generally struggled on the Section D programming as well.
A common mistake that prevented students from getting full marks was to either miss out
the code to increment the variable Count2 or to place this line outside the WHILE loop.
Q29.
Answers to Section C were often of poor quality and very few students achieved good
marks on this question. A number of students are still including additional code when
asked for the name of an identifier (parts (a) – (c), though there were fewer students this
year who were doing this. This means that they are not getting the marks for these
questions as they have not made it clear which entity is the identifier (sometimes there is
more than one identifier in the lines of code that they have copied from the Skeleton
Program).
Parts (d) – (f) were not well answered. Many students could find one error in the decision
table for part (f) but few could find more than one. Answers to parts (d) and (e) were often
vague with many students providing answers that were about different parts of the
Skeleton Program from the ones asked for in these questions.
Q30.
This was a fairly straightforward programming question with most students getting good
marks. Some students did not read the question carefully and added the line to increment
NoOfMoves inside the loop that checked for an invalid move − this would result in
NoOfMoves being incremented even if the move entered was illegal.
Q31.
For question part (a) students had to explain what a model was. Good responses
explained that, in the context of simulation, a model was an abstracted representation of
reality. Common mistakes were to explain what a physical model was and to confuse a
model with a prototype.
For part (b) students had to explain why a queue was an appropriate data structure to
represent a siding. Most students correctly explained that a stack was a first in last out
structure, which was worth one mark. Fewer went on to successfully explain how this
corresponded to the organisation of a siding. Students occasionally lost marks by using
terms such as “in front of” in relation to the wagons, when it was not clear which end of a
siding this related to.
For part (c) students had to write an algorithm for popping an item off a stack. A good
range of responses was seen, with approximately half of students achieving at least two
This question part (d), drawing an inheritance diagram, was very well answered, with
almost all students getting two marks and over half achieving all three. The most common
mistake was to represent the relationships between the classes correctly but to fail to style
the diagram appropriately.
For part (e) students had to define a class. This was well answered, with over half of
students achieving at least three of the four marks. It is clear that students’ understanding
of this topic has improved significantly over the last few years. The two most frequently
made errors were to fail to express the relationship between the ClosedWagon and
Wagon classes and to forget to override the CreateWagon procedure.
Q32.
This question was about the use of BNF to recognise language syntax. Slightly over half
of students achieved the mark for part (a).
For part (b), just under half of students achieved the mark. Good responses recognised
that an integer could contain an unlimited number of digits and that as BNF does not
support iteration, recursion had to be used to achieve this. Responses that stated that
more than one digit might be used were not enough for a mark as they did not make clear
that the number of digits was unlimited.
For part (c) students had to explain why a For loop that met the BNF syntax definition
might produce an error during compilation. Just under half of students achieved a mark for
this, with good responses including that the number used for the first limit might be higher
than the second, that the count variable might not have been declared or might be an
inappropriate type, or that count might be a reserved word in the language.
Q33.
The topics covered by this question were generally well-understood. Most students were
able to answer parts (a)-(b) and (e)-(f) well, though a number of students gave an answer
of 74 instead of -74 as the answer for part (b). For part (c), most students were not able to
state the correct range with the most common wrong answer being an upper limit of 128
(rather than 127). Many students did not read the question carefully for part 4 and
assumed that four bits were being used before the binary point when the question said
three bits before the binary point. A number of students also did not read the question
carefully for part 7 and gave answers involving the use of binary addition.
Q34.
The definitions of algorithm were normally worth one mark, with only a few students going
on to make a second creditworthy point. The decision table in part (b) was answered well,
and most students were able to get some marks on part (c). Even when students had
successfully completed part (c) they were often unable to work out what the purpose of
the algorithm was – a number of students were clearly guessing with calculating prime
numbers (an answer to a dry run question on a previous COMP1 exam), binary numbers
and Hamming code being commonly-seen incorrect answers.
Q35.
Students need to be aware that an algorithm is not the same as a program and that simply
copying the algorithm into their development environment will not result in a working
program in any of the COMP1 programming languages – the pseudo-code needs to be
adapted to match the syntax of the programming language they are using. As in previous
years, a number of students simply copied parts of the algorithm into their program code
eg trying to use a keyword of OUTPUT or students using VB.Net adding the word DO to
their WHILE loops. These appeared to be less able students who generally struggled on
the Section D programming as well.
Students who found this question difficult were often unable to create an array in the programming
language they were using. (1)
(Total 18 marks)