Top Banner
Chapter 6 Problem Solving and Algorithm Design
64

Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

Jan 03, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

Chapter 6

Problem Solving and Algorithm Design

Page 2: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

2

Problem Solving

Problem solving

The act of finding a solution to a perplexing, distressing, vexing, or unsettled question

Page 3: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

3

Problem Solving

Book: How to Solve It: A New Aspect of Mathematical Method by George Polya, 1945

"How to solve it list" written within the context of mathematical problems

But list is quite generalWe can use it to solve computerrelated problems!

Page 4: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

4

Problem Solving

How do you solve problems?

Understand the problem

Devise a plan

Carry out the plan

Look back

Page 5: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

5

Strategies

Ask questions!

– What do I know about the problem?

– What is the information that I have to process in order the find the solution?

– What does the solution look like?

– What sort of special cases exist?

– How will I recognize that I have found the solution?

Page 6: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

6

Strategies

Ask questions! Never reinvent the wheel!

Similar problems come up again and again in different guises

A good programmer recognizes a task or subtask that has been solved before and plugs in the solution

Can you think of two similar problems?

Page 7: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

7

Strategies

Divide and Conquer!

Break up a large problem into smaller units and solve each smaller problem

– Applies the concept of abstraction

– The divide-and-conquer approach can be applied over and over again until each subtask is manageable

Page 8: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

8

Algorithms

Algorithm

A set of unambiguous instructions for solving a problem or sub-problem in a finite amount of time using a finite amount of data

Why must instructions be unambiguous?

Why must time and data be finite?

Page 9: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

9

Computer Problem-Solving

Analysis and Specification PhaseAnalyzeSpecification

Algorithm Development PhaseDevelop algorithmTest algorithm

Implementation PhaseCode algorithmTest algorithm

Maintenance PhaseUseMaintain

Page 10: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

10

Phase Interactions

Page 11: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

11

Following an Algorithm

Figure 6.4 A recipe for Hollandaise sauce

Page 12: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

12

Following an Algorithm

Algorithm for preparing a Hollandaise sauceIf concerned about cholesterol

Put butter substitute in a potElse

Put butter in a potTurn on burnerPut pot on the burnerWhile (NOT bubbling)

Leave pot on the burnerPut other ingredients in the blenderTurn on blenderWhile (more in pot)

Pour contents into lender in slow steamTurn off blender

Page 13: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

13

Developing an Algorithm

Two methodologies used to develop computer solutions to a problem

– Top-down design focuses on the tasks to be done

– Object-oriented design focuses on the data involved in the solution

But first, let's look at a way to express algorithms: pseudocode

Page 14: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

14

Pseudocode

Pseudocode

A way of expressing algorithms that uses a mixture of English phrases and indention to make the steps in the solution explicit

There are no grammar rules in pseudocode

Pseudocode is not case sensitive

Page 15: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

15

Following Pseudocode

What is 93 in base 8?93/8 gives 11 remainder 511/8 gives 1 remainder 31/ 8 gives 0 remainder 1

answer 1 3 5

While ( the quotient is not zero )Divide the decimal number by the new baseMake the remainder the next digit to the left in the answerReplace the original decimal number with

Algorithm to Convert base-10 number to other bases

Page 16: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

16

Following Pseudocode

Easier way to organize solution

Page 17: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

17

Pseudocode for Complete Computer Solution

Write "Enter the new base"

Read newBase

Write "Enter the number to be converted"

Read decimalNumber

Set quotient to 1

While (quotient is not zero)

Set quotient to decimalNumber DIV newBase

Set remainder to decimalNumber REM newBase

Make the remainder the next digit to the left in the answer

Set decimalNumber to quotient

Write "The answer is "

Write answer

DIV – Operator that returns the decimal quotientREM – Operator that returns the decimal remainder

Page 18: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

18

Pseudocode Functionality

Variables

Names of places to store values

quotient, decimalNumber, newBase

Assignment

Storing the value of an expression into a

variable

Set quotient to 64

quotient <-- 64

quotient <-- 6 * 10 + 4

Page 19: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

19

Pseudocode Functionality

Output

Printing a value on an output deviceWrite, Print

Input

Getting values from the outside word and storing them into variables

Get, Read

Page 20: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

20

Pseudocode Functionality

Repetition

Repeating a series of statements Set count to 1

While ( count < 10)

Write "Enter an integer number"

Read aNumber

Write "You entered " + aNumber

Set count to count + 1

How many values were read?

Page 21: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

21

Pseudocode Functionality

Selection

Making a choice to execute or skip a statement (or group of statements)

Read number

If (number < 0)

Write number + " is less than zero."

orWrite "Enter a positive number."Read number

If (number < 0)

Write number + " is less than zero."

Write "You didn't follow instructions."

Page 22: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

22

Pseudocode Functionality

Selection

Choose to execute one statement (or group of statements) or another statement (or group of statements)

If ( age < 12 )

Write "Pay children's rate"

Write "You get a free box of popcorn"

else If ( age < 65 )

Write "Pay regular rate"

else

Write "Pay senior citizens rate"

Page 23: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

23

Pseudocode Example

Write "How many pairs of values are to be entered?"

Read numberOfPairs

Set numberRead to 0

While (numberRead < numberOfPairs)

Write "Enter two values separated by a blank; press return"

Read number1

Read number2

If (number1 < number2)

Print number1 + " " + number2

Else

Print number2 + " " number1

Increment numberRead

Page 24: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

24

Walk Through

Data Fill in values during each iteration3 numberRead number1 number2

55 70

2 1

33 33

numberOfPairs

What is the output?

Page 25: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

25

Top-Down Design

Top-Down Design

Problem-solving technique in which the problem is divided into subproblems; the process is applied to each subproblem

Modules

Self-contained collection of steps, that solve a problem or subproblem

Abstract Step

An algorithmic step containing unspecified details

Concrete Step

An algorithm step in which all details are specified

Page 26: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

26

Top-Down Design

Process continues for as many levels as it takes to make every step concrete

Name of (sub)problem at one level becomes a module at next lower level

Figure 6.5 An example of top-down design

Page 27: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

27

A General Example

Planning a large party

Figure 6.6 Subdividing the party planning

Page 28: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

28

A Computer Example

Problem

Create a list that includes each person’s name, telephone number, and e-mail address

– This list should then be printed in alphabetical order

– The names to be included in the list are on scraps of paper and business cards

Page 29: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

29

A Computer Example

Main Level 0

Enter names and numbers into listPut list into alphabetical orderPrint list

Enter names and numbers into list Level 1

While ( more names)Enter nameEnter telephone numberEnter email addressInsert information into list

Which steps are abstract? Which steps are concrete?What is missing?

Page 30: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

30

A Computer Example

Enter names and numbers into list (revised) Level 1

Set moreNames to trueWhile (moreNames)

Prompt for and enter namePrompt for and enter telephone numberPrompt for and enter email addressInsert information into listWrite "Enter a 1 to continue or a 0 to stop."Read responseIf (response = 0)

Set moreNames to false

Page 31: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

31

A Computer Example

Prompt for and enter name Level 2

Write "Enter last name; press return."Read lastNameWrite "Enter first name; press return."Read firstName

Prompt for and enter telephone number Level 2

Write "Enter area code and 7-digit number; press return."Read telephoneNumber

Prompt for and enter email address Level 2

Write "Enter email address; press return."Read emailAddress

Page 32: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

32

A Computer Example

Put list into alphabetical order

Print the list Level 1

Write "The list of names, telephone numbers, and emailaddresses follows:"

Get first item from the listWhile (more items)

Write item's firstName + " " + lastNameWrite item's telephoneNumberWrite item's emailAddressWrite a blank lineGet next item from the list

Page 33: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

33

A Computer Example

Note: Insert information is within the loop

Page 34: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

34

Testing the Algorithm

Important distinction

Mathematics

We tests the answer

Programs

We test the process

Page 35: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

35

Testing the Algorithm

Desk checking

Working through a design at a desk with a pencil and paper

Walk-through

Manual simulation of the design by team members, taking sample data values and simulating the design using the sample data

Inspection

One person (not the designer) reads the design (handed out in advance) line by line while the others point out errors

Page 36: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

36

Object-Oriented Design

Object-oriented Design

A problem-solving methodology that produces a solution to a problem in terms of self-contained entities called objects

Object

A thing or entity that makes sense within the context of the problem

For example, a student, a car, time, date

Page 37: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

37

Object-Oriented Design

World View of OOD

Problems are solved by – isolating the objects in a problem, – determining their properties and actions

(responsibilities), and – letting the objects collaborate to solve a

problem

Page 38: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

38

Object-Oriented Design

An analogy: You and your friend fix dinner

Objects: you, friend, dinner

Class: you and friend are people

People have name, eye color, …

People can shop, cook, …

Instance of a class: you and friend are instances of class People, you each have your own name and eye color, you each can shop and cook

You collaborate to fix dinner

Page 39: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

39

Object-Oriented Design

Class (or object class)

A description of a group of similar objects

Object (instance of a class)

A concrete example of the class

Classes contain fields that represent the properties (name, eye color) and behaviors (responsibilities) (shop, cook) of the class

Method

A named algorithm that defines behavior (shop, cook)

Page 40: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

40

Object-Oriented Design

Top-Down Design

decomposes problems into tasks

Object-Oriented Design

decomposes problems into

collaborating objects

Yes, but how?

Page 41: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

41

Object-Oriented Design

Steps – isolate the real-world objects in the

problem– abstract the objects with like properties

into groups (classes)– determine the responsibilities of the group

in interacting with other groups

Page 42: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

42

Object-Oriented Design

Think of design as a mapping from real world objects to classes of objects

birth date

marriagedate

dog's birth date

Date class

Objects Classes of objects

Page 43: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

43

Object-Oriented Design

Program World simulates these groups

class Date

dogBirthdate

birthdate

marriageDate

Description Instances

Page 44: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

44

Object-Oriented Design

Date'sActions inreal world

?

We call an object's interactions with other objects its

responsibilities

Create itselfKnow the state of its fields

Compare itself to another dateReturn a date #days hence

Page 45: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

45

Object-Oriented Design

Responsibilities become methods in the Program World

class DategetMonthgetDaygetYear

dogBirthdate

birthdate

marriageDate

Page 46: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

46

Object-Oriented Design Methodology

Four stages to the decomposition process

– Brainstorming to locate possible classes

– Filtering the classes to find duplicates or remove unnecessary ones

– Scenarios are tried to be sure we understand collaborations

– Responsibility algorithms are designed for all actions that classes must exhibit

Page 47: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

47

CRC Cards

CRC cards are a notational device to record informationabout a class, what is must do and with whom it mustcollaborate

Page 48: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

48

Brainstorming

A group problem-solving technique that involves the spontaneous contribution of ideas from all members of the group

– All ideas are potential good ideas– Think fast and furiously first, and ponder later– A little humor can be a powerful force

Brainstorming is designed to produce a list of candidate classes

Page 49: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

49

Filtering

Determine which are the core classes in the problem solution

There may be two classes in the list that have many common attributes and behaviors

There may be classes that really don’t belong in the problem solution

Page 50: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

50

Scenarios

Assign responsibilities to each class

There are two types of responsibilities– What a class must know about itself

(knowledge responsibilities) – What a class must be able to do (behavior

responsibilities)

Page 51: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

51

Scenarios

Encapsulation

The bundling of data and actions in such a way that the logical properties of the data and actions are separated from the implementation details

Each class encapsulates its data but shares their values through knowledge responsibilities

Page 52: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

52

Responsibility Algorithms

The algorithms must be written for the responsibilities

– Knowledge responsibilities usually just return the contents of one of an object’s variables

– Action responsibilities are a little more complicated, often involving calculations

Page 53: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

53

Computer Example

Let’s repeat the problem-solving process for creating an address list

Brainstorming and filtering– Circling the nouns and underlining the verbs

is a good way to begin

Page 54: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

Computer Example

First pass at a list of classes listnametelephone numberemail addresslistorder nameslistscrapspapercards

Filtered List

list, name, telephone number email address

Page 55: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

55

CRC Cards

Page 56: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

56

CRC Cards

Page 57: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

57

CRC Cards

How is this class different from Name and Person?

Page 58: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

58

Responsibility Algorithms

Person Class

Initialize

name.initialize()Write "Enter phone number; press return."Get telephone numberWrite "Enter email address; press return."Get email address

Print

name.print() Write "Telephone number: " + telephoneNumberWrite "Email address: " + emailAddress

Tells name to initialize itself

Tells name to print itself

Page 59: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

59

Responsibility Algorithms

Name Class

Initialize

"Enter the first name; press return."Read firstName"Enter the last name; press return."Read lastName

Print

Print "First name: " + firstNamePrint "Last name: " + lastName

Page 60: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

60

Important Threads

Information Hiding

The practice of hiding the details of a module with the goal of controlling access to it

AbstractionA model of a complex system that includes only the details essential to the viewer

Information Hiding and Abstraction are two sides of the same coin

Page 61: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

61

Important Threads

Data abstraction

Separation of the logical view of data from their implementation (e.g. Bank statement)

Procedural abstraction

Separation of the logical view of actions from their implementation (e.g. brakes of car to stop)

Control abstraction

Separation of the logical view of a control structure from its implementation (e.g. While and If)

Page 62: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

62

Important Threads

Abstraction is the most powerful tool people have formanaging complexity!

Page 63: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

63

Important Threads

Identifiers

Names given to data and actions, by which– we access the data and

Read firstName, Set count to count + 1

– execute the actionsname.initialize(), name.print()

Giving names to data and actions is a form of abstraction

Page 64: Chapter 6 Problem Solving and Algorithm Design. 2 Problem Solving Problem solving The act of finding a solution to a perplexing, distressing, vexing,

64

Important Threads

Programming language

A set of grammar rules, symbols, and special words used to construct a program

Program

A sequence of instructions written to perform a specified task

Syntax

The formal grammar rules governing the construction of valid instructions

Semantics

The rules that give meaning to the instructions