0 ratings0% found this document useful (0 votes) 68 views21 pagesChapter 12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
7
f
f
i
f
ry
fais eee
5
'
‘
Learning objectives
By the end of this chapter you should be able to:
= describe the purpose ofa structure chart
c ct rt fora given problem
programmed
scompose a problem into sub
structure chart to expr
the various module:
which are part of the algoCrna)
international AS and A level Computer Science
12.01 Stepwise refinement
Many problems that we want to solve are bigger than the ones we met in Chapter 11. To make
iteasier to solve a bigger problem, we break the problem down into smaller steps. These
might need breaking down further until the steps are small enough to solve easily.
Fora solution to a problem to be programmable, we need to break down the steps of the
ution into the basic constructs of sequence, assignment, selection, repetition, input and
utput.
In Section 11.01 we looked ata recipe
fora cake. The step of mixing together all the ingredients was broken down into more
detailed steps.
Gout
Drawing a pyramid using stepwise refinement
The problem to be solved: Take as input a chosen symbol and an odd number. Output 2
pyramid shape made up entirely ofthe chosen symbol, with the number of symbols in the
final row matching the number input.
For example the two input values Aand 9 result in the following output:
This problem is similar to Worked Example 11.09 n Chapter 11, but the number of symbols
in each row starts with one and increases by two with each row. Each row starts with a
decreasing numberof spaces, to create the slope effec.
(GRRRSEREA 2t solving this problem using structured English is:
01 Set up initial values
2 REPEAT
03 Output number of spaces
08 Output number of symbols
05 Adjust number of spaces and munber of symbols to be output in next row
06 UNTIL the required number of symbols have been output in one row
The steps are numbered to make iteasier to refer to them later
This is nat enough detail to write a program in a high-level programming language. Exactly
what values do we need to set?Chapter 12: Stepwise Refinement and Structure Charts
y
We need as input:
+ the symbol character from which the pyramid isto be formed
+ the number of symbols in the final row (for the pyramid to look symmetrical, this needs
] tobe an odd number)
We need to calculate how many spaces we need inthe frst row. So that the slope of the
pyramid is symmetrical, this number should be half of the final row's symbols. We need
to set the number of symbols to be output in the first row to 1. We therefore need the
identifiers listed in Table 12.01.
5
The character symbol to form the pyramid
‘The number of symbols in the final row
‘The number of spaces to be output in the current row
Table 12.01 Identifier table for pyramid example
Using pseudocode, we now refine the steps of our first attempt. To show which step
we are refining, a numbering system is used as shown.
‘Step 01 can be broken down as follows:
22 ee E
Remember we need an SQRfOTESMERRERESESIEEEEED ve ed to make sure
the input is an odd number. So we further refine Step 01.2: |
02.2.3 ovr, GibesoeSysc= HOSTED
02.2.4 // MoD 2 gives the remainder after integer division by 2 |
\We can now look to refine Steps 03 and 04
0 1 Output number of spaces expands into:
03.1 FOR 4 « 1 TO Numberotspaces
03.2 OUTPUT Space // without moving to next line
03.3 ENDFOR
04 © // output number of symbols expands into:
04.1 FOR i = 1 TO Nunberofsynbole
04.2 OUTPUT Symbol // without moving to next line
04.3 ENDFOR
04.4 OUTPUT Newline // move to the next linefer a at CUE Rec cg
symbols by 2:
05 // Adjust values for next row expands into:
05.1 Numberofspaces ~ NumberOtSp:
| 05.2 mumberofsymbole ~ Numberofsymbels + 2
= 1
Step 06 essentially checks whether the number of symbols for the next row is now
greater than the value input at the beginning.
| 9 ro mmerorgmote > Memabeots mole
We can put together all the steps and end up with a solution.
(GBF samanbercesymvors HOD 2 = 2
| 01.3 ‘MumberOfSpaces + (MaxNumberOfsymbols - 1) / 2
u
FOR i + 1 TO NumberOsspaces
OUTPUT Space // without moving to next line
ENDFOR
_ ee,
ourPur symbol // without moving to next line
OUTPUT Newline // move to the next line
/j Adjust Values For Next Row
o2
03
08
04.4
| or
a == m\
A first attempt at solving this problem using structured English is:
01 Setup initial values
02 REPEAT
03 Output leading number of spaces
of Output eymbol, middle spaces, symbol
05 Adjust number of spaces and number of symbols to be output in next row
06 UNTIL the required mumber of symbole have been output in one rowChapter 12: Stepwise Refinement and Structure Charts
12.02 Modules
Another method of developing a solution is to decompose the problem into sub-tasks. Each
sub-task can be considered as a ‘module’ that is refined separately. Modules are procedures
and functions.
an use this identifier when we want to refer to this group of steps, When we want to perform
the steps in a procedure we call the procedure by its name.
|
@ b)
Figure 12.01 Representation of a procedure in (a) pseudocode and (b) a flowchart
The rules for module identifiers are the same as for variable identifiers (see Section 11.03)
Piirodecuaenrs
Dray
1g a pyramid using modules
The problem is the same as in Worked Example 12.01,
When we want to set up the initial values, we calla procedure, using the following
statement:
(CALL SetValues
\We can rewrite the top-level solution to our pyramid prablem using a procedure for each
step, as:
;
on SD
i
REPEAT
ALL,
cau!
cau
vunrIL
This top-level solution calls four procedures. This means each procedure has to be defined,
‘The procedure definitions are:
CALL InputMaxtumberofsymbols // need to ensure it is an odd number
Mumberofspaces — (MaxNumberOfSynbols - 1) / 2
eee e1ery
UNTIL MaxtumberOfsymbols MOD 2 = 2
[ENDPROCEDURE
FOR Count « 1 TO NumberofSpaces
OUTPUT Space // without moving to next line
-ENDEOR
ENDPROCEDURE
FoR Count < 1 TO Wunberofsynbols
ourPUT symbol // without moving to next line
ENDFOR
OUTPUT Newline // move to the next Line
[ENDPROCEDURE
Ce ESTERS
Nunberofspaces — mumberOfspaces ~ 1
Numberotsymbols « wumberofsymbole + 2
ENDPROCEDURE
TASK 12.02
Piitodecuaens
Creating a program t Bla COnnCcEaED
Connect 4is a game played by twa players. In the commercial version shown in Figure
12.01, one player uses red tokens and the other uses black. Each player has 21 tokens,
‘The game board is a vertical grid of six rows and seven columns,
Figure 12.01 AConnect 4 board
Columns get filled with tokens from the bottom. The players take it in turns to choose
column that snot full and drop a token into this column, The token will occupy the
|
|
|
|
|
lChapter 12: Stepwise Refinement and Structure Charts
lowest empty position in the chosen column. The winner s the player who isthe frst
to connect four oftheir own tokens in a horizontal, vertical or diagonal line. fall tokens
have been used and neither player has connected four tokens, the game ends in a draw.
IF we want to write a program to play this game on a computer, we need to work out the
steps required to ‘solve the problem’, that means to let players take their turn in placing
tokens and checking fora winner. We will designate our players (and their tokens) by
“O'and x. The game board will be represented by a 2D array. To simplify the problem,
the winner isthe player who is the first to connect four oftheir tokens horizontally or
vertically.
urfirst attemptin structured English
Initialise board
Set up game
Display board
While game not finished
‘This Player makes a nove
Display beard
Check if this player has won
Té game not finished, ewap player
The top-level pseudocode version using modules is:
1 can a
02 cau
03 cant
04 WHILE GaneFinished - ESE E
05 CALL, ThisPlayertakesMove
06 CALL outputBoara
07 CARL, Checkr£thisPlayerttaston
08 IF GaneFinished = FALSE |
3 Taw |
20 CALE Swapthisplayer |
n awir
22. SNOWHTLE
Note that Steps 03 and 06 are the same. This means that we can save ourselves some
effort. We only need to define this module once, but can call it from more than one place. |
This is one of the advantages of using modules. |
The identifier table forthe program is shown in Table 12.03,
Boara(t..6, 1.7) 2D array to represent the board
TnitialiseBoard Procedure to initialise the board to all blanks
‘Setupsane Procedure to set initial values for Ganerinished and
‘ThisPlayer
GaneFinished FALSE ifthe game is not finished
TRUE. if the board is full ora player has won
ThisPlayer "0% when itis Player O's turn
‘oe when itis Player X's turn
‘OutputBoard Procedure to output the current contents of the boardThisPlayerMakestiove | Procedure to place the current player's token into the
chosen board location
CheckT£ThisPlayerHaswon| Procedure to check ifthe token just placed makes the
current player a winner
SwapthiePlayer Procedure to change player's turn
‘Table 12.02 Initial identifier table for Connect 4 game
Now we can refine each procedure (module). This is likely to add some more identifiers to
our identifier table. The additional entries required are shown after each procedure.
PROCEDURE Initialise#oard
FOR Row + 170 6
FOR Column + 1 TO 7
Board[Row, Column] + BLANK // use a suitable value for blank
ENDFOR
ENDFOR
| ENDPROCEDURE
|
Identifier Explanation
Row Loop counter for the rows
[column Loop counter for the columns,
BLANK __[Avalue that represents an empty board location
Table 12.03 Additional identifiers for the initialiceBoara procedure
PROCEDURE SetUpGame
‘ThisPlayer ~ '0' // Player 0 always starts
GameFinished ~ FALSE
[ENDPROCEDURE
PROCEDURE Outputfoard
FOR Row + 1 70 6
FOR Column = 1 TO 7
ourPuT Board[Row, Column} // don't move to next Line
ENDFOR
OUTPUT Newline // move to next line
ENDFOR
ENDPROCEDURE
PROCEDURE ThisPlayerMakestove
Validcolumn « ThisPlayerChoosesColunn // a module returne column number
ValidRow « FindNextPreePositionIncolumn // a module returns row number
Board[validRow, ValidColunn] + ThisPlayer
ENDPROCEDURE
Note that the modules ThisPlayerchoosescolumn and
FindNextFreePositionInColumn are not procedures, These modules produce
and return a value that is used in the. 2 Stennett a panne iChapter 12: Stepwise Refinement and Structure Charts
—- his value is used in an expression
Validcolunn The column number the player has chosen
ThiePlayerChoosesColumn: Function to get the current player's valid choice
of column
ValidRow The row number that represents the first free
location in the chosen column
FindNextFreePositionincolum | Function tofind the next free location in the
chosen column
Table 12.04 Additional identifiers for the ThisPiayerMakesMove procedure
roxcrron @QIBBIOVSEEROEEEBGEUND // returns a valid column number
oureur "Player * ThisPlayer "'s turn."
REPEAT
OUTEUT "Enter a valid column nunbers*
INPUT ColunnNunber
UNTIL ColumntiumberValid = TRUE // check whether the column number is valid
ENDFUNCTION
Colunnivunbervalia | Function to check whether the chosen column is valid
‘Table 12.05 Additional identifiers for ThisPlayerchoosesColuna function
Note that we need to define the function cotunatunberValia. A column is vali if itis
‘within the range 1 to 7 inclusive and theres stil at least one empty location in that colurnn,
FONCTION ColumnMumberValia // returns whether or not the column number is valid
Valid ~ FALSE
IP ColumnNumber >= 1 AND Columnumber <= 7
‘THEN
IF Board[6, ColumnNumber]= BLANK // at least 1 empty space in column
THEN
Valid + TRUE
ENDIF
ENDIF
RETURN Valid
Colunnivunber The column number chosen by the current player
y
ENDPUNCTION
Valid ate if column number is not valid
‘rRuR if column number s valid
Table 12.06 Additional identifier for the cotunnsunbervalid functionei re CCE UEC Cee
FUNCTION FindNextPreeFositionIncolumn // returns the next free posit:
Thierow + 1
WHILE Board[ThisRow, ValidColumn] <> BLANK // find first empty cell
Thiskow + Thiskow + 1
ENDWHTLE
RETURN ThisRow
ENDFUNCTION
Identifier Explanation
ThisRow Points to the next row to be checked
Table 12.07 Additional identifier for the FindwiextereePositiontnColumn function
PROCEDURE CheckrfthisPlayerliaevion
Winnerfound + FALSE
CALL Check#orizontalLinervalidRow
IF WinnerFound = FALSE
THEN
CALL CheckVerticalbinernvalidColumn
ENDIF
IF Winnerfound = TRUE
THEN
meFinished + TRUE
OUTPUT ThisPlayer * is the winner
ELSE
ENDPROCEDURE
‘ALL CheckForPullBoard
Note that the checkr#ThisPiayerHasvion procedure uses three further procedures that
weneed to
Identifier Explanation
[WinnerFound ease if no winning line
| sTRUE if a winning line is found
CheckHorizontalLineinvalidkow | proceduret.
| eck ifthere isa winning horizontal
line in the row the last token was placed in
CheckverticalLineinvalidcolumn | Procedure to checkif there is a winning vertical
line in the column the last token was placed in
[GheckForFulioard Procedure to check whether the board is full
‘Table 12.08 Additional identifiers for the checkT¢ThiePlayertiashion procedureChapter 12: Stepwise Refinement and Structure Charts
PROCEDURE CheckHorizontalLineinvalidRow
PORi + 1704
IP Board[ValidRow, i] = ThisPlayer AND
BoardiValidrow, i + 1] = ThisPlayer AND
Board[Validzow, i + 2] = ThisPlayer AND
Board[ValidRow, i + 3] = ThisPlayer
THEN
WinnerFound + TRUE
ENDIF
ENDFOR
ENDPROCEDURE
PROCEDURE CheckVerticalLineinvalidcolumn
IF validRow ~ 4 OR ValidRow ~ 5 OR ValidRow = 6
‘THEN
IF Board(Validrow, Validcolumn] = ThisPlayer AND
Board[ValidRow - 1, Validcolumn) = ThisPlayer AND
Board[ValidRow - 2, ValidColumn) = ThisPlayer AND
Board[ValidRow - 3, ValidColumn) = ThisPlayer
‘THEN
WinnerFound + TRUE
ENDIF
ENDIE
-ENDPROCEDURE
PROCEDURE CheckForFullBoard
BlankFound + FALSE
‘Thiskow + 0
REPEAT
Thiscolumn + 0
Thiskow + Thiskow + 1
REPEAT
ThisColumn + ThieColumn + 1
IF BoardlThieRow, ThisColumn} = BLANK
THEN
BlankFound ~ TRUE
ENDIF
UNTIL ThieColunn = 7 OR BlankFound
UNTIL ThisRow = 6 OR BlankFound = TRUE
IF BlankFound = FALSE
THEN
OUTPUT "Tt is a draw"
GameFinished ~ TRUE
ENDIF
ENDPROCEDURE
‘TRUE
BlankFound | gauss ifno blank location found on the board
_TRue ifa blank location found on the board
Thiskow Loop counter for rows
Thiscoluna | Loop counter for columns
‘Table 12.09 Additional identifiers for the checkForFul Board procedurembridge International AS and A level Computer Science
PROCEDURE SwapThiePlayer
IF ThisPlayer =
‘THEN
ThisPlayer ~ "x!
EISE
ThisPlayer «
ENDIF
ENDPROCEDURE
The complete identifier table for the Connect 4 program is shown in Table 12.1.
Identifier Explanation
Boardll..6, 1.71 20 array to represent the board
Tnitialiseboara Procedure toinitialise the board to all blanks
SetpGane Procedure to set initial values for
GaneFinished and ThisPlayer
GaneFinished FALSE ifthe game isnot finished
‘TRUE ifthe board is full ora player has won
ThisPlayer “o" when itis Player O's turn
x when itis Player X's turn
OutputBoard Procedure to output the current contents of
the board
i ThisPlayertakesnove Procedure to place the current player's token
L into the chosen board location
CheckIfThisPlayeriaaWon Procedure to check if the token just placed
makes the current player a winner
SvapThisPlayer Procedure to change player's turn
BLANK ‘value that represents an empty board
7 location
Validcotunn The column number the player has chosen
ThiaPlayerchoosesColunn Function to get the current player's valid
choice of column
ValidRow The row number that represents the first free
location in the chosen column
FindNextFreePositionincoluma
Inction to find the next free location in the
chosen column |
ColumnNunberValia Function to check whether the chosen |
column is validChapter 12: Stepwise Refinement and Structure Charts
WinnexPound Pause ifno winning fine
‘TRUE ifa winningline isfound
CheckHorizontalLineravaliarow | Procedure to check ifthere isa winning
horizontal line in the row the last token was
placed in
CheckVerticalbinelavalidcolunn | Procedure to checkif there isa winning
vertical ine in the column the last token was
placed in
CheckForFullboara Procedure to check whether the board is Full
BlankFoand ause ifnio blank location is found on the
board
-raur ifa blank location is found on the board
TaisRow Loop counter for rows
TaieColamn Loop counter for columns
Thiskow Points to the next row to be checked
lL
.10 Complete identifier table for Connect 4 game
Funetion: a sequence of steps that is given an identiferand retusa single value; function cals part
‘ofan expression
Note that some of the identifiers in Table 12.10 are o((9SHBBIGSnaE=rs Use OA Mtninia
Gifple HO CULel WSeaIIsUeh a araBIeaeal VaFHaBle (sec Chapter 14, Section 14.03).in Table
12.10, the local variables are highlighted. The other WaflaBIeS lable 20 se Used By Several
sub-tasks, Variables available to all modules are known as global variables (322 Cnaote- 14,
Section 14.03}
Local variable: variable thats only accessible within the module in which tis declared
Global variable: a variable thatis accessible from all modules
12.03 Structure charts
‘Analternative approach to modular design isto choose the sub-tasks andl then construct a
structure chart (0 show" interrelations between the modules. Each box of the structure
chart represents BOWUIE) Each level i a refinement of the level above.
‘Astructure chart also shows the interface between modules, the variables. Thes-variables,
are referred to as ‘parameters: A parameter supplying value to a lower-level module is
shown as a downwards pointing arrow. A parameter supplying a new value to the module at
the next higher level is shown as an upward pointing arrow.
‘Structure chart: a graphical representation of the modular structure of@ solution
Parameter: a value passed between modulesCambridge International AS and A level Computer Science
2 ture chart for a module that calculates th
The top-level boxis the name ofthe module, which is refined into th
nput numbers are passed into
rt aan OUTDD
The arrows show how the parameters ae passed between the modules,
This parameter passing is known as the ‘interface’
Levelo
interface
Level
average ‘average
Figure 12.02 Structure chart for a module that calculates the average of two numbers
‘TASK 12.03
a (SRRERREERSEB can also show control information: @SEHOABAGRSBSCSED
‘The simple number-guessing game that was introduced in Chapter 11 (Section 11.05) could
be modularised and presented as a structure chart, as shown in Figure 12.03.
Number Guessing Game
| ,
oF
S
‘As
Generate
een INPUT Guess OUTPUT message
Figure 12.08 Structure chart for number- guessing game with only one guess allowedCee aC ee rae Recs
The diamond shape shows a condition that is either True or False. So either one branch or
the other will be followed,
Figure 12.04 shows the structure chart for the pyramid-drawing program from Worked
Example 12.01. The semi-circular arrow represents repetition of the modules below the
arrow. The label shows the condition when repetition occurs.
Pyramid
Output spaces] Joutputsymbots] | Adiustvaluesfor
awNumberOSymbos
Input Max number
‘of symbols
TASK 12.04
TASK 12.05
Draw structure chart forthe followin
hana paortaeronsn wo Dari
inthe password list. The users
thecorrect gate ifthe correct} gee ‘sentered,cer
ind A level Computer Scienc:
Structure charts help programmers to visualise how modules are interrelated and how
they interface with each other. When looking ata larger problem this becomes even more
important. Figure 12.05 shows a structure chart for the Connect 4 program. Ituses the
following symbols:
+ Anarrow with a sold round en GB hows thatthe valve transferred i a flag (2
variable value(s REED
+ Adouble-headed arrow hows that t
the module.
Connect
WHILE game not finished
Seg
cae (eee Pleyermaies |[ oureur | | check game a
ffs a as ea tnished Foe
:
FYE ING
Se AAG
Ss VB
S Be
eee |b ence checker] [Cece ortt
a = Tae ed
:
en eoeerel ae acetal
eee ee in
Figure 12.05 Structure chart for the Connect 4 program
12.04 Deriving pseudocode from a structure chart
Let's look at the pyramid problem again (Figure 12.04). In Worked Example 12.02, a modular
solution was created without using a structure chart and all variables were global. Now
‘we are going use local variables and parameters. The reason for using local variables and
parameters is that modules are then self-contained and any changes to variables do not have
accidental effects on a variable value elsewhere.
The top-level module, Pyramid, calls four modules. When a module is called, we supply
the parameters in parentheses after the module identifier. This gives the following
pseudocode:Chapter 12: Stepwise Refinement and Structure Charts
MODULE Pyramid
CALL SetValues(tumberOfsymbols, Numberofspaces, Symbol, Maxiunberofsynbols)
REPEAT
CALL Outputspaces (unberOfspaces)
CALL Cutputsymbols(Mumberofsymbols, symbol)
CALL AdjustValuesForNextRow(NumberOfSpaces, NunberOfSymbols)
UNTIL Numberotsymbols > MaxtunberOfsymbols
-ENDMODULE
PROCEDURE SetValues(NunberOfSymbole, WunberOfspaces, Symbol, Maxtvunberdfsynbole)
INPUT Symbol
CALL InputMaxNumberofsynbols
Mumberofspaces « (NaxNumberOfSymbols - 1) / 2
Nunberofsynbols = 1
ENDPROCEDURE
PROCEDURE InputNaxiumberOfSymbols (MaxNunbero£symbols)
REPEAT
INPUT MaxNunberofsymbols
UNTIL Maxtumberofsymbols MOD 2 = 1
ENDPROCEDURE
PROCEDURE Output Spaces MumberOfSpaces)
FOR Count © 1 10 NunberOfspaces
OUTPUT Space // without moving to next Line
‘ENDFOR
[ENDPROCEDURE
PROCEDURE Outputsymbols(umberofsynbols, Symbol)
FOR Count + 1 10 Nunberofsynbols
ourpur symbol // without moving to next line
ENDEOR
OUTPUT Newline // move to the next line
ENDPROCEDURE
PROCEDURE AdjustValuesForNextRow(NunberOfspaces, NunberOfsynbols)
NumberOfSpaces + NumberOfSpaces - 1
MumberOfsymbole + MunberOfsymbola + 2
ENDPROCEDURE
Discussion Point:level Computer Science
‘Stepwise refinement involves breaking down the steps of an outline solution into smaller and
smaller steps (sub-tass).
‘Stepwise refinement is used to produce a solution that can be stated in terms ofthe four basic
constructs of sequence, assignment, selection and repetition.
‘© Each sub-task can be written asa module,
'© Modules are either procedures or functions.
‘© Aprocedureis a sequence of steps that are given an identifier. A procedure can be called
‘whenever this sequence of steps should be followed.
‘function isa sequence of steps that are given an identifier. This sequence of teps results ina single
value thats returned from the function, A function callis part ofan expression orassignment.
Local variables are variables that are used within a single module.
Global variables are variables that are used throughout the solution.
‘Structure charts are graphical representations ofthe modular structure of solutions,
A structure chart shows the interface between modules: parameters passed between the calling,
module and the module being called.
‘Structure charts show selection, where 3 modules called only under certain conditions.
‘© Structure charts show repetition, where modules are called repeatedly.
Exam-style Questions
1
he structured English version of the algorithm is
Theidentifiers required are:
Identifier Explanation
TALEO | 10 array to storethe countof how many
times each number has been generated
(RRS [The random number generated
Numberoftests | The number of times a random number isto
be generated
ExpectedFrequency | The number of times any one number would
be generated ifall numbers are generated
equally frequently (1000/20 in this example}eee ie ee race
@ Complete the structure chart below by naming the labels A to E:
a 8 Update Tay ourpur ray
b Produce pseudocode from the structure chart.
A game toe BEUSESIRERIORBs played as follows:
+ There an
+ Each pictureis on @SMiereneearaS)
+The cards are placed face down in random order as an 88 grid pattern,
+ Two players take tuns
+ When tis player's tur, the player chooses two cards and tums them face up so the pictures show.
+ lfthe pictures are the same, the player takes the pair of cards, gains a point and has another go
+ lithe pictures are not the same, the cards are turned face down again
+ Allplayers can see the up-turned pictures and memorise ther grid postions
+The game finishes when all cards have been paired.
+ The layer with the most pointsis the winner
The problems to design an algorithm that
+ puts64 cards into random positions into an 8 8 table
+ after the input oftwo sets of co-ordinates shows the chosen cards fora shart time
‘removes the cards there is @ match
+ Updates the player's points
+ outputs the numberof points for both players when there are no more cards (the game has finished}
For the purpose of this algorithm
+ The pictures are to be represented by the numbers 1to 32
+ Agrid position with no card isto be represented by 0
The identifiers required are:
Id ites Explanation
Table to store the card values
Points[1..2] List to store the points for player 1 and player 2
|[tnisblayer The number ofthe curent lave
Gane aan wile thee are cards etn the gid
{RUE when ll cards have been taken
me The co-ordinate plrsf the two cards chosen bythe current player
av
@
1]Cambridge International AS and A level Computer Science
Top-level algorithm:
a
o2
a
on
05
06
09
20
na
CALL SetupEmptyGrid
CALL RandomlyDistributecards
CALL SetUpPlayers
GaneEnd « FALSE
REPEAT
CALL GetPlayersCoordinates
CALL Displaycria
CALL TestFormatch
CALL TestForEndcane
onrn,
cat
Whatisthe name gven to the method of breaking the above steps down into smaller steps? a
Complete the following procedures:
PROCEDURE
FOR ie 1708
FOR} #2708
- 1] assign grid elements
ENDFOR
ENDFOR
[ENDPROCEDURE
PROCEDURE RandomlyDistributecards
FOR Number < 1 TO 32
CALL GetEmptyGridPosition
Gridbx, y) © Number We
CALL GetEmptyGridPosition
W place second card with this number
e firet card with this number
ENDPOR
[ENDPROCEDURE
PROCEDURE GetEmptyGridPosition
REPEAT
x © Randonlfunber(1,) // generate a random number between 1 and 8
y © Randonliumber(i,8) // generate another random number
owTrL W find al
[ENDPROCEDURE
PROCEDURE SetupPlayers
SEGRERTATIE 9) // both players start wich 0 points
‘ThisPlayer © 2
ENDPROCEDURE
PROCEDURE GetPlayersCoordinates
REPEAT
ul oc: TIES and is not in the same position as first card
UNITE ( ‘AND ea
-ENDPROCEDURESe Ue ake
PROCEDURE DisplayGrid
FORi #1708
FOR} ©1708
IF (i = x1) AND (j = y1)__// dt is the chosen card
‘THEN
oureor GD...
4
is
1° QED - 0 // ve card in this position has been renoved
Em
Corse pene
mise // back of card to be whows an 7°
OUTEU wessssssresetse
sore
aor?
Exoron
Exor0a
woenoceDURE
=
7 watch found, de
Griaina, ya) @ oe :
Griate2, yal © 4
71 Anccemant. potnes
Pointe(Thieplayer]
st
Cau svapetayers
ENDIF
-ENDPROCEDURE
PROCEDURE SwapPlayers
ENDPROCEDURE
soins seers
=
ete
aeeee
PROCEDURE OutputResults
‘ENDPROCEDURE 8)
© Drawa structure chart for this problem. 05)