Presentation is loading. Please wait.

Presentation is loading. Please wait.

Higher Computing Science Standard Algorithms

Similar presentations


Presentation on theme: "Higher Computing Science Standard Algorithms"— Presentation transcript:

1 Higher Computing Science Standard Algorithms
This webinar will be recorded and will be available on the Scholar website shortly afterwards. Don't worry if you have missed something – you can view it at your leisure later on. Throughout this webinar I'll be using a special type of pseudo-code called Haggis. This is actually what is known as a reference language because it has a formal syntax. This means that it can be converted to code no matter what programming language you are using in school.

2 Standard Algorithms Input Validation (from National 5)
Finding the Maximum / Minimum Counting Occurrences Linear Search You will have covered input validation at National 5, but we are going to look at it in a little more detail. I'll be introducing functions and parameters in some of the code as well. Don't worry if you haven't covered that yet, but knowing about them will be useful when you come to do your coursework programming tasks. Although you need to know the standard algorithms, when you encounter them in an exam you are likely to be asked to use them in context, so you will need to be able to adapt them to new circumstances. You can't just learn them off by heart.

3 Standard Algorithms Other than input validation the other 3 standard algorithms are ways of extracting different pieces of information from an array

4 Input Validation Input validation can be achieved in two ways:
Restrict the data the user can input by only presenting them with a limited set of possibilities such as a drop box or pull down menu, Accept the input but reject any which does not meet the restrictions imposed by the software and ask them to input it again. This second approach is the one we are going to examine. Although drop down options can make life simpler in some situations, there are times when the user has to enter data on the keyboard. Can you give me an example?

5 The validInteger function
FUNCTION validInteger()RETURNS INTEGER DECLARE userInput AS INTEGER INITIALLY 0 RECEIVE userInput FROM KEYBOARD WHILE userInput < 1 OR userInput > 100 DO SEND "Input must be between 1 and 100" TO DISPLAY END WHILE RETURN userInput END FUNCTION This algorithm uses a conditional loop

6 The validInteger function
We would call this function within a program: SET number TO validInteger To give the variable number a value between 1 and 100 This could have been written as a procedure with a parameter but using a function makes the code more readable when it is used in a program

7 The validInteger function with parameters
FUNCTION validInteger(lowerLimit, upperLimit)RETURNS INTEGER DECLARE userInput AS INTEGER INITIALLY 0 RECEIVE userInput FROM (INTEGER) KEYBOARD WHILE (userInput < lowerLimit) OR (userInput > upperLimit) DO SEND "Input must be between" & lowerLimit "and" & upperLimit TO DISPLAY RECEIVE userInput FROM KEYBOARD END WHILE RETURN userInput END FUNCTION This function has two formal parameters. These are value parameters. Value parameters are ones which do not change their value inside the sub program

8 Calling the validInteger function
We could call this function with actual parameters, 1 and 50 to return a number between 1 and 50: SET numberToUse TO validInteger(1,50) or we could call it with the actual parameters 1 and inputRange which is a variable which has a value assigned elsewhere in the program: SEND "What is the maximum input value" TO SCREEN RECEIVE inputRange FROM (INTEGER) KEYBOARD SET numberToUse TO validInteger(1,inputRange) This function call would return a value between 1 and inputRange. So if we wanted several different inputs from the user with different upper and lower limits, we can use the same input validation function each time, but calling it with different actual parameters.

9 Input validation (String)
FUNCTION validInput()RETURNS STRING DECLARE userInput AS STRING INITIALLY "" SEND ["Please enter Y or N"] TO DISPLAY RECEIVE userInput FROM KEYBOARD WHILE userInput ≠ ["Y"] AND userInput ≠ ["N"] DO SEND "Input must be Y or N " TO DISPLAY END WHILE RETURN userInput END FUNCTION This is the same algorithm modified to accept a string

10 Input Validation procedure with a boolean flag
PROCEDURE getValidInput(INTEGER lengthLimit) DECLARE userInput AS STRING INITIALLY "" DECLARE validInput AS BOOLEAN INITIALLY false REPEAT RECEIVE userInput FROM (STRING) KEYBOARD IF length(userInput) < lengthLimit THEN SET validInput TO true ELSE SEND "Input must be less than "& lengthLimit & "characters" TO DISPLAY END IF UNTIL validInput = true END PROCEDURE

11 Input Validation with a boolean flag
In this version of the algorithm the boolean variable validInput is set to false at the beginning, and the conditional loop only terminates once it has been set to true. This version of the algorithm is useful if you want to check a number of different conditions in the input string, for example the length of a string as well as what characters it contains If you need to check several conditions - for example, the length of the string and whether it contains specific characters or not, you would use a conditional statement to set the Boolean flag to false inside the loop for each condition that was not satisfied.

12 Iterating through arrays
Finding the maximum / minimum value Counting occurrences Linear search The next 3 algorithms all iterate through an array using the array index to identify each element in turn. Iteration is just a name for stepping through the index values of an array. Note that the numbering of items in an arrays starts with zero.

13 Finding the Maximum SET largest TO <value of the first item in array> FOR <each of the remaining items> DO IF <value of item> > largest THEN SET largest TO <value of item> END IF END FOR SEND largest TO DISPLAY This algorithm uses a fixed (unconditional) loop because we have to check every item in the array

14 Finding the Maximum PROCEDURE findMax (ARRAY OF INTEGER numbers)
SET maxValue TO numbers[0] FOR counter FROM 1 TO 9 DO IF maxValue < numbers[counter] THEN SET maxValue TO numbers[counter] END IF END FOR SEND "The largest value was "& maxValue TO DISPLAY END PROCEDURE Why do I start the loop at index value 1? This algorithm finds the maximum value in an array of 10 items

15 Finding the Minimum SET smallest TO <value of the first item in array> FOR <each of the remaining items> DO IF <value of item> < smallest THEN SET smallest TO <value of item> END IF END FOR SEND smallest TO DISPLAY This algorithm uses a fixed (unconditional) loop because we have to check every item in the array

16 Finding the Minimum PROCEDURE findMin (ARRAY OF INTEGER numbers)
SET minimumValue TO numbers[0] FOR counter FROM 1 TO 9 DO IF minimumValue > numbers[counter] THEN SET minimumValue TO numbers[counter] END IF END FOR SEND "The smallest value was " & minimumValue TO DISPLAY END PROCEDURE

17 Counting Occurrences <Ask for targetValue to count>
SET numberFound TO 0 FOR <every item in the array> IF <item is equal to targetValue> THEN <add 1 to numberFound> END IF END FOR SEND numberFound TO DISPLAY Counting Occurrences uses a fixed (unconditional loop) because we have to check every item in the array

18 Counting Occurrences PROCEDURE countOccurrences (ARRAY OF INTEGER numbers) RECEIVE itemToFind FROM (INTEGER) KEYBOARD DECLARE numberFound AS INTEGER INITIALLY 0 FOR EACH item FROM numbers DO IF item = itemToFind THEN SET numberFound TO numberFound + 1 END IF END FOREACH SEND "There were " & numberFound) "occurrences of " & itemToFind " in the list" TO DISPLAY END PROCEDURE

19 Linear Search <Input targetValue from user> SET found TO false SET counter TO 0 REPEAT IF myArray[counter] = targetValue THEN SET found TO true END IF <add 1 to counter> UNTIL found IF counter > length(myArray) THEN SEND "Not found" TO DISPLAY SEND "Found at position" counter TO DISPLAY This is perhaps the most complex algorithm, because we need to take account of the fact that the target value may not be found. Also we do not need to check every item in the array if we find what we are looking for before the end. For this reason we use a conditional loop. This algorithm will only find the first occurrence of the item searched for.

20 Linear Search PROCEDURE linearSearch (ARRAY OF INTEGER numbers)
RECEIVE itemToFind FROM (INTEGER) KEYBOARD DECLARE found AS BOOLEAN INITIALLY false DECLARE arraySize AS INTEGER INITIALLY length(numbers) DECLARE counter AS INTEGER INITIALLY 0 REPEAT IF numbers[counter] = itemToFind THEN SET found TO true END IF SET counter TO counter + 1 UNTIL found OR counter > arraySize IF found THEN SEND itemToFind & "found at position" & counter - 1) TO DISPLAY ELSE SEND "Item not found" TO DISPLAY END PROCEDURE

21 Linear Search This line:
PROCEDURE linearSearch (ARRAY OF INTEGER numbers) RECEIVE itemToFind FROM (INTEGER) KEYBOARD DECLARE found AS BOOLEAN INITIALLY false DECLARE arraySize AS INTEGER INITIALLY length(numbers) DECLARE counter AS INTEGER INITIALLY 0 REPEAT SET found TO numbers[counter] = itemToFind SET counter TO counter + 1 UNTIL found OR counter > arraySize IF found THEN SEND itemToFind & "found at position" & counter - 1) TO DISPLAY ELSE SEND "Item not found" TO DISPLAY END IF END PROCEDURE This line: SET found TO numbers[counter] = itemToFind Is equivalent to the IF numbers[counter] = itemToFind THEN SET found TO true END IF

22 Linear Search (unconditional loop)
PROCEDURE linearSearch (ARRAY OF INTEGER numbers) RECEIVE itemToFind FROM (INTEGER) KEYBOARD DECLARE found AS BOOLEAN INITIALLY false FOR EACH item FROM numbers DO SET found TO numbers[counter] = itemToFind IF found THEN SEND itemToFind & "found at position" & item) TO DISPLAY END IF END FOR IF found = false THEN SEND "item not found" TO DISPLAY END PROCEDURE This version of the algorithm uses an unconditional loop and will find every instance of the search item in the array

23 SQA Past paper Questions
2016 Q10a, Q13, Q15c 2015 paper Q3 2015 paper Q14b Exemplar Paper Q9a Exemplar Paper Q9b 2013 (old Higher) Q22 2011 (old Higher) Q15 2010 (old Higher) Q17e

24 2016 Q10a Mrs McColl is a computing teacher who creates a program to grade her pupils’ work. Mrs McColl’s students have had two tests, one in Software Design and Development (SDD) and one in Information Systems Design and Development (a) Using pseudocode, or a programming language of your choice, write an algorithm for a subroutine that will count the number of pupils who achieved a grade B in both tests.

25 2016 Q10a SET total TO 0 FOR counter FROM 0 TO 5 DO
IF SDD[counter] = "B" AND ISDD[counter] = "B" THEN SET total TO total + 1 END IF END FOR SEND ("The total number of pupils attaining a B in both tests was " & total) TO DISPLAY

26 2016 Q13a Eloïse wants to search for an item of data held in an array. She writes the following algorithm. Line SET list TO [71,76,66,67,89,72] Line SET target TO 71 Line SET found TO false Line FOR counter FROM 0 TO 5 DO Line IF list[counter] = target THEN Line SET found TO true Line ELSE Line SET found TO false LINE END IF LINE END FOR LINE IF found =true THEN LINE SEND “Item found” TO DISPLAY LINE ELSE LINE SEND “Not found” TO DISPLAY LINE END IF

27 2016 Q13a A trace table is shown below which shows the line numbers where a variable has changed. State the missing values at A, B, C and D line list target counter found 1 [71,76,66,67,89,72] 2 A 3 B 4 6 C 8 D 71 False True False

28 2016 Q13a The algorithm is incorrect and so outputs the wrong message.
Explain why the algorithm is incorrect. Describe how to correct the algorithm

29 2016 Q13a Remove lines 7 and 8 SET list TO [71,76,66,67,89,72]
SET target TO 71 SET found TO false FOR counter FROM 0 TO 5 DO IF list[counter] = target THEN SET found TO true ELSE END IF END FOR IF found = true THEN SEND “Item found” TO DISPLAY SEND “Not found” TO DISPLAY Remove lines 7 and 8

30 2016 Q13a SET list TO [71,76,66,67,89,72] SET target TO 71 SET found TO false SET counter TO 0 REPEAT IF list[counter] = target THEN SET found TO true END IF SET counter TO counter + 1 UNTIL found OR counter > 5 IF found = true THEN SEND “Item found” TO DISPLAY ELSE SEND “Not found” TO DISPLAY OR Use a conditional loop until found is true (or end of list)

31 2016 Q15a Tony coaches a team of eight elite athletes for a 400 metre race. Tony uses a program to help analyse each athlete’s performance. A sample of the data held on each athlete is shown below. Tony has added a record structure to his program. RECORD athleteData IS {STRING forename, STRING surname, INTEGER runnerNumber, BOOLEAN professional, REAL seasonBest, REAL weight} Tony wants to store his eight athletes’ data using the record structure shown above. The variable name is athletes. Using pseudocode, or a programming language of your choice, declare the variable which can store the data for the eight athletes. DECLARE athletes[7] AS athleteData

32 2016 Q15c Tony wants to find the fastest 400 m time of the season.
Using pseudocode, or a programming language of your choice, design an algorithm to find the fastest season time. Your answer should use the variable declared in part (a). DECLARE athletes[7] AS athleteData SET minimum TO athletes[0].seasonBest FOR counter FROM 1 TO 7 DO IF athletes[counter].seasonBest < minimum THEN minimum = athletes[counter].seasonBest END IF END FOR SEND minimum TO DISPLAY

33 2015 paper Q3 This algorithm uses an unconditional loop
An online company uses a computer program to display particular customer records. The algorithm of this program is shown below. Line 1 SET found TO false Line 2 RECEIVE search_name FROM (STRING) KEYBOARD Line 3 FOR counter FROM 0 TO <End Of List> DO Line 4 IF name[counter] = search_name THEN Line 5 SET found TO true Line 6 SEND name[counter] & counter TO DISPLAY Line 7 END IF Line 8 END FOR Line 9 IF found = false THEN Line 10 SEND “Name not found” TO DISPLAY Line 11 END IF The following data is stored in the name array: Jimmy, Samina, Kate, Jimmy, Adam State the output from the above program if Jimmy is entered at line 2 from the keyboard. This algorithm uses an unconditional loop

34 2015 paper Q3 [ Jimmy, Samina, Kate, Jimmy, Adam ] Jimmy 3 Jimmy 0
Line 1 SET found TO false Line 2 RECEIVE search_name FROM (STRING) KEYBOARD Line 3 FOR counter FROM 0 TO <End Of List> DO Line 4 IF name[counter] = search_name THEN Line 5 SET found TO true Line 6 SEND name[counter] & counter TO DISPLAY Line 7 END IF Line 8 END FOR Line 9 IF found = false THEN Line 10 SEND “Name not found” TO DISPLAY Line 11 END IF So both instances of Jimmy are found Jimmy 0 Jimmy 3

35 Q14b Rowena accidentally entered an invalid mobile phone number and an error message is displayed. A valid mobile phone number will consist of a string of 11 digits. Using pseudocode or a programming language of your choice, write the algorithm which would check that the mobile phone number is valid.

36 Q14b Possible answer REPEAT RECIEVE mobileNumber (STRING)FROM KEYBOARD DECLARE valid INITIALLY True IF length(mobile_number) <> 11 THEN SET valid TO false ELSE FOR counter FROM 1 TO 11 DO IF (mid(mobileNumber, counter, 1) < "0") OR (mid(mobileNumber, counter, 1) > "9") THEN SEND "error" TO DISPLAY END IF END FOR UNTIL valid = true

37 Exemplar Paper Q9a A record data structure is used for the members’ details. RECORD Members IS {STRING surname, STRING forename, STRING username, INTEGER password} Describe how the website could store the information for five million members, using the record data structure above. DECLARE people [ ] AS ARRAY OF Members

38 Exemplar Paper 9b When someone logs on, a search is performed using the Username that they entered. Using pseudocode, or a language with which you are familiar, write an algorithm that asks for a Username and then finds the position of that Username.

39 Exemplar Paper 9b SET found TO false SET counter T0 -1
SET position TO 0 RECEIVE targetname FROM (STRING) KEYBOARD REPEAT SET counter TO counter +1 IF people[counter].username=target THEN SET found TO true SET position TO counter END IF UNTIL counter = OR found = true SEND position TO DISPLAY

40 2013 Q22 A horse race produced the set of results shown below. The names and times are held as two lists. (a) (i) Use pseudocode to design an algorithm that would store the time of the winning horse in the variable fastest. (ii) The time for the Slowest horse is also to be identified. Other than the change of variable name, state one change that would have to be made to your algorithm for part (i) to achieve this. (iii) The number of horses who have a race time greater than 8 minutes is also to be identified. State the name of a standard algorithm that could achieve this. Name Mister McGee Kelly’s Hero Fred’s Folly The Tool Ins Fizzy Lizzie Time: Minutes 8·15 7·12 8·65 9·15 7·08

41 2013 Q22 PROCEDURE findFastest (ARRAY OF INTEGER horseTimes)
SET fastest TO horseTimes[0] FOR counter FROM 1 TO 4 DO IF fastest > horseTimes[counter] THEN SET fastest TO horseTimes[counter] END IF END FOR SEND "The fastest was "& fastest TO DISPLAY END PROCEDURE

42 2013 Q22 Change > to < Counting Occurrences
A horse race produced the set of results shown below. The names and times are held as two lists. (a) (i) Use pseudocode to design an algorithm that would store the time of the winning horse in the variable fastest. (ii) The time for the Slowest horse is also to be identified. Other than the change of variable name, state one change that would have to be made to your algorithm for part (i) to achieve this. (iii) The number of horses who have a race time greater than 8 minutes is also to be identified. State the name of a standard algorithm that could achieve this. Name Mister McGee Kelly’s Hero Fred’s Folly The Tool Ins Fizzy Lizzie Time: Minutes 8·15 7·12 8·65 9·15 7·08 Change > to < Counting Occurrences

43 2011 Q15 RightIT, a software company, is currently developing a cash machine program for a bank. The cash machine will offer five options to customers. The options selected during a day are stored as a list. The bank would like the software to calculate the number of times the mobile top-up option appears on this list. Use pseudocode to design an algorithm to carry out this calculation.

44 2011 Q15 PROCEDURE countTopups(ARRAY OF STRING options) SET total TO 0 FOR EACH item FROM options IF item = "mobile" THEN SET total TO total + 1 END IF END FOR SEND " total & "mobile topups" TO DISPLAY END PROCEDURE

45 2010 Q17e A subprogram in building management software is used to find the range of temperatures in a building in one day. The temperature is recorded every 15 minutes within a 24 hour period and stored in a list. Use pseudocode to design one algorithm to find both the highest and lowest temperatures in this list.

46 2010 Q17e PROCEDURE findMaxMin(ARRAY OF INTEGER temp) SET min TO temp[0] SET max TO temp[0] FOR counter FROM 0 TO 95 IF temp[counter] > max THEN SET max TO temp[counter] IF temp[counter] < min THEN SET min TO temp[counter] END FOR SEND "Maximum = " & max TO DISPLAY SEND "Minimum = " & min TO DISPLAY END PROCEDURE

47 Counting Occurrences example
At the end of each round of an archery competition, those players who have a score which is the same or greater than the qualifying score are selected for the next round. The software is required to count the number of players who have qualified. Use pseudocode to design an algorithm to carry out this calculation. State the data structure which will be used to store the players’ scores.

48 Counting Occurrences example
The data structure is an INTEGER array PROCEDURE countQualifiers (ARRAY OF INTEGER scores) SET Number_qualified TO 0 FOR each archer_score FROM scores IF archer_score >= qualification_score THEN SET Number_qualified TO Number_qualified +1 ENDIF END FOR SEND "Qualifiers = "& Number_qualified TO DISPLAY END PROCEDURE

49 Linear search example Customers are given a unique ID number when they register with their employer. Customer ID’s are created using the first 3 letters of the customers surname and the last 3 letters of their postcode. This ID is stored in a 1-D array. For example: Mr J Brown with a postcode of EH15 6NW has a customer ID of BRO6NW Using a design notation with which you are familiar, write an algorithm that would find a particular customer ID from the array.

50 Linear search example PROCEDURE findEmployee(ARRAY OF STRING employees) SET found TO false SET counter TO 0 RECEIVE target_ID FROM (STRING) KEYBOARD REPEAT SET found TO employees[counter] = target_ID SET counter TO counter + 1 UNTIL found OR counter > total_employees IF found THEN SEND ["Found at position " & counter] TO DISPLAY ELSE SEND ["Not found"] TO DISPLAY END IF END PROCEDURE The line SET found TO employee[counter] = target_ID Is a concise form of: IF employee[counter] = target_ID THRN SET found TO true END IF

51 Cycle Race: What Data Structure?
Race times Names Nationalities Qualifiers real array string array boolean array

52 Cycle Race: What standard algorithm?
Find the best race time Find how many cyclists were from Scotland Find the name of the winner Find Bradley’s time Find how many qualified

53 Cycle Race: What standard algorithm?
Best race time Find the minimum from the raceTimes array Name of winner match to the names array Cyclists from Scotland Count occurrences from the nationalities array Bradley’s time Linear search the names array then match to the raceTimes array Qualifiers Count occurrences from the qualifiers array

54 Cycle Race The preferred application for this set of problems is a database – manipulating arrays is exactly what is happening behind the scenes in a database application.


Download ppt "Higher Computing Science Standard Algorithms"

Similar presentations


Ads by Google