640 likes | 783 Views
Objectives. By the end of this lecture, students should: understand what an algorithms is appreciate the role of algorithm definitions in the problem solving process know the basic components of algorithms understand the difference between algorithms and programs
E N D
Objectives • By the end of this lecture, students should: • understand what an algorithms is • appreciate the role of algorithm definitions in the problem solving process • know the basic components of algorithms • understand the difference between algorithms and programs • be able to formulate algorithms for simple problems • Reading: Walter Savitch. An Introduction to Problem Solving and Programming, Pearson, 2004. Sec. 1.1-1.3
How do we solve problems? • We "just do" • Guesswork-and-luck • Trial-and-error • Experience (possibly someone else's) • Systematically !
The Problem-solving Process "Doctor, my head hurts" Patient has elevated pressure in anterior parietal lobe. Analysis Problem specification 1. Sterilize cranial saw 2. Anaesthetize patient 3. Remove top of skull 4. Get the big spoon... 5. etc., etc. Design Algorithm Implementation sterilize(saw,alcohol); raise_hammer(); lower hammer(fast); start(saw); /* etc. etc. */ Program Compilation 010011101011001010101010100101010101010011001010101010100101101001110101010101001001011101001111010101011111010101000110100001101... Executable (solution)
...it’s not a linear process Problem Idea Informal Description Refinement Coding Algorithm Program Testing & Debugging
Algorithm • A sequence of instructions specifying the steps required to accomplish some task • Named after:Muhammad ibn Musa al-Khwarizmi of Khowarezm (now Khiva in Uzbekistan) Circa 780-850 C.E. (Common Era)
Algorithm –History Muhammad ibn Musa Al-Khwarizmi http://www-groups.dcs.st-andrews.ac.uk/~history/Mathematicians/Al-Khwarizmi.html • Book on arithmetic: • Hindu numeration, decimal numbers, use of zero, method for finding square root • Latin translation (c.1120 CE): “Algoritmi de numero Indorum” • Book on algebra • Hisab al-jabr w’al-muqabala
Algorithm – Working Definition • A sequence of instructions describing how to do a task [As opposed to actually executing the instructions]
Algorithm -- Examples • A cooking recipe • Assembly instructionsfor a model • The rules of how to play a game • VCR instructions • Descriptionof a martial arts technique • Directions for driving from A to B • A knitting pattern • A car repair manual
Algorithm -- Examples • A cooking recipe • Assembly instructionsfor a model • The rules of how to play a game • VCR instructions • Descriptionof a martial arts technique • Directions for driving from A to B • A knitting pattern • A car repair manual
Algorithms are not Programs • Algorithms are well-defined sequence of unambiguous instructions • must terminate (to produce a result) • Algorithm description relies on a well-defined“instruction language” • Example: Manual AdditionDescribe the method! 123456 + 789001912457
Algorithm – Examples (cont) • Recipe for Almond and honey slice • Recipe for Arroz con pollo
1/2 quantity Shortcrust Pastry 185 g unsalted butter 100 g castor sugar 5 tablespoons honey 50 ml cream 50 ml brandy or any other liqueur or spirit 300 g flaked almonds Preheat oven for 200° C Line a 30 cm 20 cm baking tray with baking paper, and then with pastry Bake blind for 20 minutes, then remove weights and foil Turn oven up to 220° C. Bring remaining ingredients to a boil, stirring. Spread evenly over pastry. Bake until topping is bubbling and has caramelised evenly, about 15 minutes. Cool before cutting into fingers or squares. Almond and Honey Slice From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.
1/2 quantity Shortcrust Pastry 185 g unsalted butter 100 g castor sugar 5 tablespoons honey 50 ml cream 50 ml brandy or any other liqueur or spirit 300 g flaked almonds Preheat oven for 200° C Line a 30 cm 20 cm baking tray with baking paper, and then with pastry Bake blind for 20 minutes, then remove weights and foil Turn oven up to 220° C. Bring remaining ingredients to a boil, stirring. Spread evenly over pastry. Bake until topping is bubbling and has caramelised evenly, about 15 minutes. Cool before cutting into fingers or squares. Almond and Honey Slice Instructions are given in the order in which they are performed (“executed”) From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.
Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil. Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and sauté until onion is golden. Add bay leaf, whole tomatoes, and chicken broth. When the broth boils add salt, saffron and rice. Arrange chicken on rice, cover casserole and bake in a moderate oven (350°F) for 20 minutes or until the rice is tender. Add beans and artichokes during last 10 minutes of cooking. Correct Algorithm? From: “Arroz Con Pollo” in The Margaret Fulton Cookbook, Hamlyn, Sydney, 1968.
Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil. Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and sauté until onion is golden. Add bay leaf, whole tomatoes, and chicken broth. When the broth boils add salt, saffron and rice. Arrange chicken on rice, cover casserole andbake in a moderate oven (350°F) for 20 minutes or until the rice is tender. Add beans and artichokes during last 10 minutes of cooking. Correct Algorithm? From: “Arroz Con Pollo” in The Margaret Fulton Cookbook, Hamlyn, Sydney, 1968.
Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil. Remove the chicken and to the juices in the casserole add garlic, onions and green peppers, and sauté until onion is golden. Add bay leaf, whole tomatoes, and chicken broth. When the broth boils add salt, saffron and rice. Arrange chicken on rice, cover casserole andbake in a moderate oven (350°F) for 10 minutes. Add beans and artichokes. Cover, and bake for another 10 minutes or until rice is tender. Correct Algorithm?
Algorithm: A sequence of instructions describing how to do a task (or process) Problem Program From Algorithms to Programs
Algorithms are not Programs • always design the algorithm before you start to program, • the idea comes before the coding.
How to get out? Example
Example “run through the maze always sticking to the wall on your left” repeat if “no wall left” then turn left, step ahead else if “no wall ahead” then step ahead else turn right until “at exit”
Algorithms and Languages • the very same Algorithm may look very different when described (or implemented) in different (programming-) languages, e.g. “Sum up the numbers between 1 and 10 by adding each of them to a total starting with 0” s +/( 10) APL-styleint s:=0; for i = 0 to 10 do s:= s+i; end Pascal-style
Components of an Algorithm • Input and Output Specification • Variables and values • Instructions • Sequences • Selections • Repetitions • Abstraction Mechanisms • Objects • Methods Also required: Documentation
Values • Represent quantities, amounts or measurements • May be numerical or alphabetical(or of some other defined “type”) • Example: • Recipe ingredients
1/2 quantity Shortcrust Pastry 185 g unsalted butter 100 g castor sugar 5 tablespoons honey 50 ml cream 50 ml brandy or any other liqueur or spirit 300 g flaked almonds Preheat oven for 200° C Line a 30 cm 20 cm baking tray with baking paper, and then with pastry Bake blind for 20 minutes, then remove weights and foil Turn oven up to 220° C. Bring remaining ingredients to a boil, stirring. Spread evenly over pastry. Bake until topping is bubbling and has caramelised evenly, about 15 minutes. Cool before cutting into fingers or squares. Almond and Honey Slice From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.
1/2 quantity Shotcrust Pastry 185 g unsalted butter 100 g castor sugar 5 tablespoons honey 50 ml cream 50 ml brandy or any other liqueur or spirit 300 g flaked almonds Preheat oven for 200° C Line a 30 cm 20 cm baking tray with baking paper, and then with pastry Bake blind for 20 minutes, then remove weights and foil Turn oven up to 220° C. Bring remaining ingredients to a boil, stirring. Spread evenly over pastry. Bake until topping is bubbling and has caramelised evenly, about 15 minutes. Cool before cutting into fingers or squares. Almond and Honey Slice From: Stephanie Alexander, The Cook’s Companion, Viking/Penguin, Ringwood, Victoria, 1996, p. 349.
Variable Values 10 cookies 50 grams of sugar 3 slices of cake etc. This jar can contain Variables Are containers for values– placesto storevalues Example:
Restrictions on Variables • Variables may be restricted to contain a specific type of value
Components of an Algorithm • Values and Variables • Instruction (a.k.a. primitive) • Sequence (of instructions) • Selection (between instructions) • Repetition (of instructions) • Abstractions (with Objects and Methods) • Documentation (beside instructions)
Instructions(Primitives) • Some action that is • simple • unambiguous • that the system knows about... • ...and should be able to actually do
Instructions – Examples Directions to perform specific actions on values and variables. • Take off your shoes • Count to 10 • Cut alongdotted line • Knit1 • Purl 2 • Pullrip-cord firmly • Sift 10 grams of arsenic
Instructions -- Application • Some instructions can only be applied to a specific type of values or variables • Examples: Chop
Instructions(Primitives) -- Recommendations • When writing an algorithm, make each instruction simple and unambiguous • Example: Cut chicken into pieces. Heat olive oil in a casserole dish. Brown the chicken pieces in the casserole dish. Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.
Components of an Algorithm • Values and Variables • Instruction (a.k.a. primitive) • Sequence (of instructions) • Selection (between instructions) • Repetition (of instructions) • Abstractions (with Objects and Methods) • Documentation (beside instructions)
Instruction (Primitives) A “sequence” of simple instructions • When writing an algorithm, make the instructions simple and unambiguous. • Example: Cut chicken into pieces. Heat olive oil in a casserole dish. Brown the chicken pieces in the casserole dish. Cut chicken into pieces and brown the pieces on all sides in a casserole dish in hot olive oil.
Sequence • A series of instructions • ...to be carried out one after the other... • ...without hesitation or question • Example: • How to cook a Gourmet MealTM
Sequence -- Example 1. Open freezer door 2. Take out Gourmet Meal™ 3. Close freezer door 4. Open microwave door 5. Put Gourmet Meal™ on carousel 6. Shut microwave door 7. Set microwave on high for 5 minutes 8. Start microwave 9. Wait 5 minutes 10. Open microwave door 11. Remove Gourmet Meal™ 12. Close microwave door
Components of an Algorithm • Values and Variables • Instruction (a.k.a. primitive) • Sequence (of instructions) • Selection (between instructions) • Repetition (of instructions) • Abstractions (with Objects and Methods) • Documentation (beside instructions)
Selection • An instruction that decides which of two possible sequences is executed • The decision is based on a single true/false condition • Examples: • Car repair • Reciprocals
Selection Example -- Car Repair if (motor turns) then { CheckFuel CheckSparkPlugs CheckCarburator } else { CheckStarterMotor CheckEngineBlock }
Selection Example –Car Repair (cont) if (motor turns) then { CheckFuel CheckSparkPlugs CheckCarburator } else { CheckStarterMotor CheckEngineBlock } Should be a true or false condition.
Selection Example --Car Repair (cont) if (motor turns) then { CheckFuel CheckSparkPlugs CheckCarburator } else { CheckStarterMotor CheckEngineBlock } Sequence if the condition is true.
Selection Example --Car Repair (cont) if (motor turns) then { CheckFuel CheckSparkPlugs CheckCarburator } else { CheckStarterMotor CheckEngineBlock } Sequence if the condition is false.
Selection Example -- Reciprocals Examples: Reciprocal of 2: 1/2 Reciprocal of -3/4:1/(-3/4) = -4/3 Reciprocal of 0:“undefined” Q. Give an algorithm for computing the reciprocal of a number.
Algorithm: input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity" } Selection Example – Reciprocals (cont) Q. Give an algorithm for computing the reciprocal of a number.
Selection Example-- Reciprocals Algorithm: input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity" } Num is a variablewhose value depends on the actual number the user provides.
Selection Example – Reciprocals (cont) Algorithm: input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity" } Condition depends on the value of Num
Selection Example – Reciprocals (cont) Algorithm: input Num if (Numis not equal 0) then { output 1/Num } else { output "infinity" } For a given value of Num, only one of these two sequences can be executed
Selection Example – Reciprocals (cont) Algorithm: input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity" } Executed if Num is not equal to 0
Selection Example – Reciprocals (cont) Algorithm: input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity" } Executed if Numis equal to 0
Selection -- Exercise Will the following algorithms produce the same output? Algorithm 1: input Num if (Num is not equal 0) then { output 1/Num } else { output "infinity" } Algorithm 2: input Num if (Num is not equal 0) then { output 1/Num } output "infinity"