0% found this document useful (0 votes)
384 views31 pages

2.1 Workbook Answers

Uploaded by

lululush267
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
384 views31 pages

2.1 Workbook Answers

Uploaded by

lululush267
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

GCSE J277 Unit 2.

1 | Algorithms Craig’n’Dave

Specification and learning objectives


By the end of this topic, you will have studied:
• Principles of computational thinking: Abstraction, decomposition, algorithmic thinking
• The inputs, processes and outputs of a problem
• Structure diagrams
• Creating, interpreting, correcting and refining algorithms using: Pseudocode, flowcharts, reference/high-level language
• Identifying common errors
• Trace tables
• Standard searching algorithms: Binary search, linear search
• Standard sorting algorithms: Bubble sort, merge sort, insertion sort

Resources
We recommend the OCR-endorsed text book from PG Online for use during your GCSE studies.
Craig ‘n’ Dave videos for SLR 2.1
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Abstraction

Abstraction means: Including the necessary details and leaving out the unnecessary details when solving a problem.

Example of abstraction:

Real aeroplane: Paper aeroplane: Necessary features of a paper aeroplane:

• Easy and quick to construct


• Wings
• Shape
• Gliding performance

Unnecessary features of a paper aeroplane:

• Tail
• Windows
• Decals
• Engines
• Landing gear
• Cockpit
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Abstraction
Cat: Cat icon: Necessary features of the icon: Unnecessary features of the icon:

• Ear shape • Fur


• Eye shape • Eye colour
• Whiskers • Body and legs

Dog: Dog icon: Necessary features of the icon: Unnecessary features of the icon:

• Ear shape • Fur


• Nose shape • Face detail
• Body and legs
• Colour

Rabbit: Rabbit icon: Necessary features of the icon: Unnecessary features of the icon:

• Raised ears • Fur


• Ear shape • Mouth
• Face shape • Body and legs
• Colour and shadow
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Abstraction
A computer program outputs whether a capital city in Europe is north or south of another capital city in Europe. It only needs to know the latitude of the two
cities – the other detail is unnecessary. This is an example of abstraction; including the necessary detail and not including the unnecessary detail.

City Latitude (N)

Dublin 53.3498

London 51.5074

Oslo 59.9139

Paris 48.8566

Madrid 40.4168

Program:
city = input("Enter city:")
latitude = float(input("Enter
latitude:"))

if latitude < 51.5074 then


print("The city is south of London")
else
print("The city is north of London")
endif
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Decomposition

Decomposition means: Breaking a problem down into smaller sub-problems, making the overall problem easier to solve.

Examples of problem decomposition in everyday life:

Making toast: Making a fairy cake:

1. Start by getting your toppings ready – take your 1. Preheat the oven to 180C/350F/Gas Mark 4.
butter out of the fridge so it can come up to 2. Line your cake tin with paper cases.
[Picture of toast room temperature. [Picture of fairy 3. Cream the butter and sugar together in a bowl until
here] 2. Get your jam or marmalade out of the fridge or cake here] the mixture is pale. Beat in the eggs a little at a time
cupboard. and stir in the vanilla extract.
3. Get your plate and knife ready. 4. Fold in the flour using a large metal spoon.
4. Cut yourself two slices of bread. 5. Add a little milk until the mixture is a soft dropping
5. If you're using a toaster, set the control for how consistency and spoon the mixture into the paper
well-done you want the toast to be before you cases until they are half-full.
put it in. Push the button down and the toast 6. Bake them in the oven for 8 – 10 minutes or until
will pop up when it's ready. they’re golden-brown on top and a skewer inserted
6. If you’re using the grill, preheat it to high. into one of the cakes comes out clean.
7. Once it's nice and hot, put your slices of bread 7. Set them aside to cool for 10 minutes, then remove
under the grill to toast. them from the tin and place them on a wire rack.
8. Keep an eye on it, and when you've got a good 8. For the icing, sift the icing sugar into a large mixing
colour, carefully pull them out and flip each slice bowl and stir in enough water to create a smooth
over with some tongs. mixture. Stir in the food colouring.
9. Toast the other side until it’s done. 9. Drizzle the icing over the cakes, sprinkle them with
10. Spread the butter on the toast. decorations and set them aside until the icing
11. Spread the topping on the toast. hardens.
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Decomposition and structure diagrams

Advantages of decomposition include: 1. Making problems easier to solve by breaking them down.
2. Different people can work on different parts of a problem, reducing development time.
3. Program components developed in one program can be reused in other programs.

Example of problem decomposition in calculating the cost of


1. Using the length of the chain and the size of the beads, calculate how many
producing costume jewellery:
beads will be required.
2. Multiply the number of red beads by the cost of the red beads.
3. Multiply the number of purple beads by the cost of the purple beads.
4. Add the cost of the chain plus the beads.

Red beads

Chain

Purple beads
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Decomposition and structure diagrams

The advantages of using structure diagrams when designing a solution are:

• Programs are easier to write – a solution can be reached quicker. Wages program
• Programs are easier to test.
• Programs are less prone to mistakes and errors during development.
• Multiple programmers can work on a program at the same time.
• If program requirements change during development, which is quite
common, the program is easier to change. Calculate
Calculate wage Print wage slip
• Maintaining the program is easier. deductions

Calculate basic
Calculate tax
wage

Calculate
Calculate
National
overtime
Insurance
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Decomposition and structure diagrams

Structure diagram for a pupil management program:

Pupil
management
program

Pupil
Pupils on roll LEA funds
attendance

Add new pupil Income

New pupil
Expenditure
application

Remove pupil

Clearly, there are many other possible solutions to this problem – and that in
itself can be the basis for a decent class discussion.

Students should be awarded for understanding the principles of breaking


down a problem, not for reproducing this exact example solution.
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Identify the input, processes and outputs for a problem

An input is: Any information or data which goes into a system.

A process is: Anything which happens to information or data during a programs execution e.g. performing calculations or convertions

An output is: Any information of data which leaves a system.

Title of program What does it do? Inputs Processes Outputs

width : real
Swimming pool volume Calculates the total volume length : real Volume = width * length * volume : real
of a swimming pool depth
depth : real
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Algorithmic thinking

Decomposition of pick-up sticks:


1. Set the number of sticks to 27.
2. Set the player number to 1
3. While sticks > 0:
1. Output whose turn it is.
2. Output the number of sticks left.
3. Set the sticks chosen to 0.
4. While the player has not chosen one, two or three sticks:
a) Input the number of sticks to pick up.
5. Subtract the number of sticks picked up from the pile.
6. If the number of sticks is less than one, the player loses – otherwise, change the player
number.
4. Output who won the game.
Program:
sticks = 27
player = 1
while sticks >0:
print()
print("Player",player,"it's your turn.")
print("There are",sticks,"sticks")
chosen = 0
while chosen <1 or chosen >3:
chosen = int(input("Enter the number of sticks to pick
up:"))
sticks = sticks - chosen
if player == 1:
player = 2
else:
player = 1
print("Player",player,"wins!")
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Algorithmic thinking

Decomposition of noughts and crosses:


1. Draw the empty board:
a) Two vertical lines
b) Two horizontal lines
2. While no player has won and it is not a draw:
a) While the player has not chosen a square or an invalid square is chosen:
i. Input the square for the player move.
b) Draw the player move on the board.
c) If nine moves have not been made, calculate the computer’s move:
i. If the player can win on their next move, choose the square to block them.
ii. ElseIf the middle square is free, choose the middle square.
iii. ElseIf a corner square is free, choose a corner square.
iv. Else choose any free square.
d) Draw the computer’s move on the board.
e) Check if the player has won:
i. Check for a horizontal line.
ii. Check for a vertical line.
iii. Check for a diagonal line.
f) Check if the computer has won:
i. Check for a horizontal line.
ii. Check for a vertical line.
iii. Check for a diagonal line.
g) If there is a winner, output who won.
h) Check if it is a draw.
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Linear search

Explanation of a linear search: Starting from the beginning of a list, each item is checked in turn to see if it is the one being searched for.

Steps to find the Geography 1. Check if Archaeology is Geography: no.


book using a linear search: 2. Check if Art is Geography: no.
3. Check if Biology is Geography: no.
4. Check if Chemistry is Geography: no.
5. Check if Computing is Geography: no.
6. Check if English is Geography: no.
7. Check if French is Geography: no.
8. Check if Geography is Geography: yes.
9. Book found.

Pseudocode of the linear book = ["Archaeology", "Art", "Biology", "Chemistry", "Computing", "English",
search algorithm: "French", "Geography", "History", "Maths", "Psychology"]

found = False
number = 0
find = "Geography"
WHILE found == False AND number < LEN(book):
IF book[number]==find:
found = True
number = number + 1
IF found == True:
PRINT “True”
ELSE:
PRINT “False”
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Binary search

Explanation of a binary search: Calculate the mid-point and check if that is the item being searched for. If not, and the item is lower than the mid-point,
repeat on the left half of the list. If the item is higher than the mid-point, repeat on the right half of the list.

Steps to find the Geography 1. Calculate the mid-point:


book on the shelf using a 11 books divided by 2 = 5.5
binary search: Round down to 5
2. Check the fifth book: Computing
3. Not found. Geography is greater than
Computing alphabetically, so find the
mid-point of the right half of the list:
6 / 2 = 3.
4. Check the eighth book (5 + 3 = 8):
Geography
5. Book found.

Special condition for a binary search to work: The data items must be in order.

In most cases, the quicker search is the: binary search algorithm. However, this is not true if the first item in the list is the one being searched for.

If the item you want to find is first in the list, the linear search algorithm would be quicker.
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Binary search

Pseudocode of the binary book = ["Archaeology", "Art", "Biology", "Chemistry", "Computing", "English",
search algorithm: "French", "Geography", "History", "Maths", "Psychology"]

found = False
left = 0
right = LEN(book)-1
find = "Geography"

WHILE found == False and left<=right:


mid = (left + right) // 2

IF book[mid]==find:
found = True
ELSE:
IF find>book[mid]:
left = mid + 1
ELSE:
right = mid - 1

IF found == True:
print("True")
ELSE:
print("False")
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Bubble sort

How a bubble sort works: Note how 32 has “bubbled” to the top – The algorithm has been optimised, so it does not check the
this is how the bubble sort got its name. numbers already bubbled to the top. It can also stop if no
swaps are made after all the numbers are checked.

24 24 24 24 32 32 32 32 32 32

8 8 8 32 24 24 24 24 24 24

16 16 32 8 8 8 16 16 16 16

2 32 16 16 16 16 8 8 8 8

32 2 2 2 2 2 2 2 2 2

Check 2 Check 32 Check 32 Check 32 Check 2 Check 16 Check 16 Check 2 Check 8 Check 2
and 32 and 16 and 8 and 24 and 16 and 8 and 24 and 8 and 16 and 8
Swap Swap Swap Swap No swap Swap No swap No swap No swap No swap
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Merge sort

How a merge sort works:

82 82 82
82 82

9 9 9
9 43

3 3 43 38
43

43 43 3 27
38

27 9
27 38 27

38 3
38 27 3

Original list Split list until Swap number Merge adjacent Until all lists
lists have two pairs if necessary lists together are merged
numbers
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Merge sort

How a merge sort works:

24 24 24

Step
24 H 32

8 16
Ste I
8
pC 32 Step 24

16 8
D
16 ep 16 16
St Step G
Ste
pB
32 32 32 8 8
Step F

2 2 2 2 2
Step A Step E

Original Split into Swap numbers Merge adjacent lists together Merge adjacent lists together
list adjacent sub- if necessary in by comparing the first number by comparing the first number
lists of up to two each sub-list in each list, moving the in each list and moving the
numbers 8 and 16 swap smaller number into a new smaller number into a new
list, one number at a time list, one number at a time
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Insertion sort

How an insertion sort works:

24 24 24 24 24
Yellow dotted box:
unsorted data

8 8 8 8
32

16 16 16
32 24

2 2
32 16 16

32
32 16 8 8

8
Green solid box:
sorted data 32 2 2 2 2

32 inserted 2 inserted 16 inserted 8 inserted 24 inserted


in place in place in place in place in place
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Flowchart symbols

Represents the start or Represents the input


Terminal Input/Output
end of the process. or output of data.

Represents something being Represents a subroutine call that


Process initialised, processed Subroutine will relate to a separate,
or calculated. non-linked flowchart.

Represents a decision with yes/no Line


Represents control passing
Decision or true/false that results in two
between connected shapes.
lines for the two outcomes.
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

How to produce algorithms using flowcharts

An algorithm for a role-playing game


displays three choices from a menu
to the user:
1. Play game
2. Change character START
3. Quit

The user input is validated so only


the numbers 1 – 3 can be entered.
Output menu choices

Input player choice

Is choice No
>0 and <4

Yes

END
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Interpret, correct, refine or complete algorithms.

An algorithm for a role-playing game do


displays three choices from a menu print(“1. Play game”)
to the user: print(“2. Change character”)
1. Play game print(“3. Quit”)
2. Change character
3. Quit input(int(choice))

The user input is validated so only until choice<1 AND choice>4


the numbers 1 – 3 can be entered. Should be 3

Should be OR
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

How to produce algorithms using flowcharts

An algorithm for a role-playing game


handles a battle between two player START
characters.

Each character has an attack and


defence attribute that must be input
by the user before an engagement. Input p1attack dice = random number 1-12

When the two characters engage, a


random number between 1 and 12 is Input p1defence Total2 = dice + p2attack + p2defence
generated for each player.

The attack attribute plus the defence


attribute is added to the player's roll. Input p2attack
Is total1 >
If player 1’s total is greater than total2
player 2’s total, player 1 wins – Input p2defence
otherwise, player 2 wins. Yes No

The winner is output.


dice = random number 1-12
Output P1 wins Output P2 wins

Total 1 = dice + p1attack + p1defence

END
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

How to produce algorithms using pseudocode (OCR reference language)

An algorithm for a role-playing game input int(p1attack)


handles a battle between two player input int(p1defence)
Casting the input
characters. input int(p2attack)
input int(p2defence)
Each character has an attack and
defence attribute that must be input dice = random(1,12)
by the user before an engagement. total1 = dice + p1attack + p1defence Random number function
Concatenating the total
When the two characters engage, a dice = random(1,12)
random number between 1 and 12 is total2 = dice + p2attack + p2defence
generated for each player.
if total1 > total2 then
The attack attribute plus the defence print("Player 1 wins")
Selection with a condition
attribute is added to the player's roll. else
print("Player 2 wins")
If player 1’s total is greater than endif
player 2’s total, player 1 wins –
otherwise, player 2 wins.

The winner is output.


GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Interpret, correct, refine or complete algorithms

Modified algorithm to correct an input int(p1attack)


issue with player 2 winning more input int(p1defence)
battles than player 1: input int(p2attack)
input int(p2defence)

do
dice = random(1,12)
total1 = dice + p1attack + p1defence

dice = random(1,12)
total2 = dice + p2attack + p2defence Eliminate a draw resulting in player 2
being declared the winner by re-running
if total1 > total2 then the algorithm with new random numbers.
print("Player 1 wins")
endif
if total1 < total2 then
print("Player 2 wins")
endif
until total1 != total2

Note: Python does not support DO loops, so for a Python program, you will
need this code instead of the DO UNTIL structure:
total1 = 0
total2 = 0
while total1 == total2:
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Interpret, correct, refine or complete algorithms

An algorithm for a role-playing game function randomcaverns(n)


generates a list of random caverns caverns = []
into which objects will be placed. for c = 1 to n
valid = TRUE
Should be FALSE
Caverns are numbered from 1 – 50. while valid = FALSE
The number of caverns to return is n. r = random(1,50)
valid = FALSE Should be TRUE
for i = 0 to caverns.LENGTH
if caverns[i] = r then valid = FALSE endif
next i
endwhile
caverns[c] = c
next c Should be c, not r
return caverns
endfunction
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

How to produce algorithms using flowcharts

A role-playing game allows a player


to input their next move by entering START
N, E, S or W. Valid moves are stored
in a list like this: move = [0,1,0,1]
Zero means the move is not possible. m="N" Yes
One means it is possible. The AND
possibilities are stored in the list in vm[0]=1
the order: N, E, S, W.
No
A function takes two parameters: m="E"
m is the move: N, E, S or W. vm is a Yes
AND
list of the valid moves. vm[1]=1

Assume a zero-indexed list/array. No


m="S" Yes
AND
vm[2]=1

No
m="W"
Yes
AND
vm[3]=1
No
Return Return
False True

END
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

How to produce algorithms using pseudocode (OCR reference language)

A role-playing game allows a player function valid_move(m,vm)


to input their next move by entering
N, E, S or W. Valid moves are stored if m == "N" and vm[0] == 1 then
in a list like this: move = [0,1,0,1] return True
Zero means the move is not possible. elseif m == "E" and vm[1] == 1 then
One means it is possible. The return True
possibilities are stored in the list in elseif m == "S" and vm[2] == 1 then
the order: N, E, S, W. return True
elseif m == "W" and vm[3] == 1 then
A function takes two parameters: return True
m is the move: N, E, S or W. vm is a else
list of the valid moves. return False
endif

endfunction

valid_moves = [0,1,0,1]
move = "W"

print(valid_move(move,valid_moves))
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Identifying common errors and suggesting fixes


01: input (int(p1attack))
02: input (int(p1defence))
03: input (int(p2attack))
04: input (int(p2defence))
05:
06: dice = random(1,12)
07: total1 = dice + p1attack + p1defence
08:
09: dice = random(1,12)
10: total2 = dice + p2attack + p2defence
11:
12: if total1 > total2 then
13: print(Player 1 wins)
14: else
15: print("Player 2 wins")
16: endif

The error is on line: 13

The type of error is: syntax

To fix this error: Strings must be enclosed in quotation marks. Missing this will cause the computer to assume Player1 is a variable. It
then won’t understand what 1 wins means. The correct line would be:

print("Player 1 wins")
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Identifying common errors and suggesting fixes


01: input (int(p1attack))
02: input (int(p1defence))
03: input (int(p2attack))
04: input (int(p2defence))
05:
06: dice = random(1,12)
07: total1 = dice + p1attack + p1defence
08:
09: dice = random(1,12)
10: total2 = dice + p2attack + p2defence
11:
12: if total1 < total2 then
13: print("Player 1 wins")
14: else
15: print("Player 2 wins")
16: endif

The error is on line: 12

The type of error is: logical

To fix this error: As currently written if total1 (which is player 1’s score) is less than total2 (which is players 2’s) score then print that
Player 1 has won, which is wrong, they have lost! The less than symbol needs to change to a greater than symbol:

if total1 > total2 then


GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Identifying common errors and suggesting fixes


01: input (int(p1attack))
02: input (int(p1defence))
03: input (int(p2attack))
04: input (int(p2defence))
05:
06: dice = random(1 12)
07: total1 = dice + p1attack + p1defence
08:
09: dice = random(1 12)
10: total2 = dice + p2attack + p2defence
11:
12: if total1 > total2 then
13: print("Player 1 wins")
14: else
15: print("Player 2 wins")
16: endif

The error is on line: 06 and 09

The type of error is: syntax

To fix this error: The random function takes two parameters (integers) which must be separated by a comma, the comma is missing:

dice = random(1,12)
GCSE J277 Unit 2.1 | Algorithms Craig’n’Dave

Trace tables

Assuming the user enters the values: 01: x = int(input("Enter a number: "))
• Line 01: x = 2 02: y = int(input("Enter another number:
• Line 02: y = 7 "))
complete the trace table for this program. 03:
04: total = x
05:
X=2 Y=7 total counter 06: for counter = 1 to y
07: total = total * x
2 7 2 1 08: print(total)
4 2 09: next counter

8 3
16 4
32 5
64 6
128 7

You might also like