UMAP MODULE477 Computer Problem

advertisement
UMAP MODULE477
MODULES
AND
MONOGRAPHS
IN
UNDERGRAOUATE
MATHEMATICS
ANDITS
APPLICATIONS
F > F > F >
b
.
-
b
?
!
.
n
HerbertL. Dershem
a
' > ' > ^
O
D
Computer
Problem
Solving
b
l
n
l
S
N
$
N
f
S
N
> , @ > . @ > . @
^
/,
o
/'\
> . ; , o
- g t
q
2
'
r,t "
>
g
< t
c
2
q
Z
t,r '
I,t
6
^- s
x
! l x
6 = x :
$
t s
t *
a
^
t
^
--
€
' o
e
t
^
N
,
c . ' l e - l q . ' l
BilkhauserBostonlnc.
380 Green Street
Cambridge,MA0A39
Computer
Science/Algorilhms
Inl,enpduld?
Title:
Desctiotion
Sheet:
UMAPL'hnt 477
PROBI,EM
SOLVIN6
COMPUTER
-Autho!:
Herbefi L. Dershen
Departnent of Conputer Science
Hope College
H o ll a n d . M i c hi g r n 4 9 4 2 5
R e v i e wS t a g e / D a t e :
classification:
IV
6/30/8r
coMpuTERscI/ALGoR|IIMS
Plerequisite Sklrrs I
None
Output 5ki1ls:
l . B e a b l e t o e ^ p l a i n t h e c o n c e p to f a l g o r i t h m a n d b e a b l e
solution
algorithns fron non-algorlthmic
to dlstinguish
descriptions.
in the floY_
2. Be able to read and explain algolithns {ritten
chart language.
5. Be able to state the seven steps in conpute! problea solving
and be able to apply their in solving simPle Paoblels.
Iterat-f;64
coripur et Prblen
Sor!\^e
(Itnit
478)
@ 198r EDC/Project Ult{AP
A11 rights rese ed.'
MODU],!SAND MONOGMPHS]N UNDERGRADUATE
MATHEMATICS
AND ITS APPLICATIONS
PROJECT(IJMAP)
The goal of UIIAP is to develop, through a con nunity of users and
developers, a systen of instructional
nodules ir undergraduate nathentatics and its applications that nay be used to supplenent exlsting
courses and fron which cotnplete courses nay eventually be built.
The Project is guided by a National Advisory Board of nathenaticians, scientists,
and educators.
Ul,tAPis funded by a grant frorn th€
National Science Foundation to Education Developnent Center, Inc., a
publicly supported, nonprofit cor?oration engaged in educational research in the U.S. and abroad.
PROJECT
STAIF
Ross L. Finney
SolononA. Carfunkel
Felicia M. DeMay
Barbara Kelczeuski
Paula M. Sanlillo
DonnaDiDuca
Project Director
Executive Director, CoMAP
Associate Dir€ctot
Coordinato! for Materials Production
Assistant to the Directors
Projebt Secretary/Production Assistant
Zachaly zevitas
Staff Assistant
UMAPADVISORY
BOARD
Steven J. Brans
Lleyron Clarkson
DonaldA. Lalson
R. DuncanLuce
Frederick Most6ller
GeorgeM, Miller
l{a1t€r Sears
Amold A. Strassenburg
Alfred B. Wll1cox
NswYork University
Texas Southen University
SUNYat Buffalo
Haftard Univorsity
Harvard University
NassauConununityCollege
ljniversity of Michigan Prsss
SUNYat Stony Bloot
Mathenatical Association of Ainerica
This unit was field-tested andlor studont review€d in prelinrinary
forn by Harold Baker of Litchfield High School; Donald F. Bailey of
Cometl College; AIex C. Bsnn€tt of Brenerton High Schoor; Ls!?y So$der
of Northern lllinois
Univslsity;
and t{, Thumon l,{hitley of Univ€rsity of
Ne Haven and has be€n revised on the basis of dara rocsived fron these
The Ploject woutd like to thank Carol Stoles of Danville Area
Co'tnunity CoIlege, DaDville, Illinois;
Ray Treaduay of Bennett
College, Greensboro, North Carolina; Douglas F. Hale of the University
of Texas-Pernian Basin, odessa, Teras; Carloll 0. lvilde of the Naval
Postgraduate Schoot, Monterey, Califonia;
and one anonynous revlewer,
for their leviewsj and all othe?s who assisted in the productior of this
unit.
This naterial uas prspared ith the partial
suppo?t of National
Science Foundation Grant No, SED80-07731. Reconnrendations e)eressed are
thoss of the autho! and do not necessarily reflecr the views of the NSF
.r
rha
.^nvri
dhr
h^rrar
COMPUTTR
PROBI,EMSOLVING
by
Hexbett L. Dershen
Departnent of Cornputer Science
Hoge College
Ho11and, Michigan
49423
TABLE OF CONTENTS
1 . INTRODUfl'ION
2 , ALGORITHMS
3.
TLOTCHART
LA]IGUAGE
4.
P R O B LSEO
ML V I N
SG
TEPS
5.
AN 8XA},'PLE
6.
ANSI,I'BRS
TO EXERCISBS
7.
MoDB!EXAI,{
8.
SOLUTIONS
TO MODBL
EXAM
,,,,.I2
l4
. .
30
31
.
,:1r
l:..i'!.:
l
j
INTRODUCTION
M u c ho f a p e r s o n ' s l i f e i s s p e n t i n s o l v i n g p r o b l e n s .
Usua11y, e use a tool or a set of tools to assist us in
solving those problens.
F o r e x a n p l e , w h e n f a c e d 1 ^ r i t ht h e
problen
of transporting
nyself from where I anr now to a
location across town where I would like to be, I night
use an autonobile as a tool.
If I an faced with the
problen of remov-ing
t h e c o n t e n t s o I a c a p p e db o t t l e , a
bottle-opener i,ould be an appropriate tool , In somecases,
I n e e d t o u s e a c o m b i n a t j o no f t o o l s I-or e,(anpIe.il I
had to renoye the contents of a capped bottle that was in
a store across toun, I uould use both the autonobile and
the bottle-opener.
lor
nany problens that peopLe nced to so1vc, the
computer is an appropTia!e too1, Bu! the computer is
just a too.li it r,,iI1 not solve a problemby itsclf.
The
conputer can assist you in solving a problen only if you
know hov to utilize
it
correctly"
This module introduces
techniques and ideas which you nrayapply when using the
computer to solve problens.
Although we are prinarily
concerned with lhe use of
cornputersin the problen solving process, the techniques
are applicable to other nodes of solving problens.
2,
ALGORITHMS
task in solving a problemis Iinding
4ppropriate ways of representing the solution process.
The nore carefully this is done, the easier the ptoblen
solvlng process. An algorithn is a connon way of repreThe first
senting the soluiion
this tern.
process, so we begin by defining
-1-
Definition
of an Algorith]n
An ordered set of rules for solving a problen is
called aD dlgorithn if it has t]te fo1lo{ing properties:
1.
z.
3.
the rules are unanb-lguous.
The rules are in a ProPer seguence.
The procedure specified by the set of ruLes
sol1/es the problen.
The procedure terninates sfter a finite nunber
of steps, o! actions sPecified bY the rules.
Wevi11 "back into" en understanding of l}lhet an
aLgorithn is by first considering whdt one i s t r ' t .
N o h a l g o r i t f u n1 .
1.
Directions for getting to the hospital.
Govest on Tenth Street until you cone to a
stoplight.
2 . Turn onto River Avenue a! the stoPlight.
3 . Make a light at the Y on Rive! Avenue.
4 . The hospital lri1] be on your right a fe
last
blocks
the Y.
Unfortunately, ue have el1 been tho recipiients, and
probably the givers as ve11, of nonalgorithnic directions
like these. I hope your illness is not too scute in this
case because if it is, you flay terninate befofe tho
algorithn does, The problen vith this nonalgorithn is
thdt lt violat€s condition 1 by bei4g anbiguous' In
rule 1, which stop light is DeEnt? In tule 2' which way
should I turn? At the Y describod in rule 3, there is a
right fork and a sharP :'ight turn possible. I'Jhich should
I take? Hownany blocks are a few in step 4?
Nonalgorithfi
1
2.
3,
4.
5.
2,
Directions
for
pass lng an exaln'
G e t l o t s o f s l e e P t h e night befote
outline the naterial.
R e a dt h e n a t e r i a l .
Listen attentively in c l a s s .
Take the exanination.
-2-
the eJa6I['
This nonalgorithr contains rules rhat miCht be
adequate to solve the probler0, but they cannot be
carried out in the specified order.
Thus the rules are
p
r
o
p
e
r
not in
sequence, and condition 2 of the algorithn
d ef i n l t i o n i s v i o l a t e d .
Nonalgorithn 5.
.L
l3.
Directions for passing a true-fatse
Bring a coin Lo Lhe test,
Flip the coin for each iten on the rest.
If the coin lands heads respond with true,
the coin lands tai1s,
test
if
respond with fa1se.
There is no anbiguity in this nonatgorithn, and
steps are in ploper sequence. Th€ only difficulty
is
y
o
u
that unless
have an unusually intelligent
(tucky?)
coin,
this procedure nay not solve the problen at hand,
1 4 ' h i c hi s t o p a s s t h e t e s t ,
Hence, condition 3 of the
definition is violated.
Nonalqorithn 4.
1.
2.
3.
Directions
for naking a nillion
doltars.
Get 10 nillion dimes.
Go to Las Vegas.
Play the dine slot nachines until either
(or r ore) dines or until
have 20 nillion
you
you
run out of them.
d
lf
w.,,
r,,n
^,,i
^f;in.-
5.
If you reach 20 nillion
a h e a dI
^-
uar^
LU s LrP
rr
dines, quit while you're
you oblain the supply of dines needed in
s t e p l a n d t h e c r a n k i n g p o r , u en
r eeded in step 3, this
procedure is 5till
a nonalgofithn because i! tnaynever
terninate:
there is no guarantee that you will ever
Even lf
obtain the desired result a! step 3.
in the definition is violated.
Hence, condition 4
Now we a?e ready to consider an exarnple which does
qualify as an algorithn under our definition.
5-
Find the greatesl
1'
Algorithn
given nunbers, N and M.
connon divisor
of two
3-
N and M'
Let K be the srnalle|of
If K divides both N and M, then K is the
greates t connon divisol'
Otherwise, subtract 1 fron K'
4.
Go to step 2.
1.
2-
is unanbiguous, its rules are 1n
This algorithn
so in
proper sequence, it so1ves the problen, and it does
It is also very sinple and
a finite nunber o! steps.
However, it nay take a long tine to
easv to foflow.
For exanple'
solve the probLen using this elgorithn'
2
i f 1 5 7 9 8 4 3 3a n d 5 6 6 8 3 2 a r e u s e d f o r N a n d M , s t e p
woulil be executed 566783 tines before the correc!
that
algorjthn'
A nore efficieflt
enslrer of 49 is found.
is, one thet can solve the sNne ProbLetr with much less
is known and we she11 pfesent 1! nexr'
effolt,
Algorithn 2, Given two nunbers' N and M' find thei!
greatest cotMon divisor.
1.
2.
4.
N i.s srneller then M, then exchange the tl'ro'
Divide N by M and call the renainder R'
If the rendinder R is zero, then M is the GCD'
the value of M and M to the
othernise, set N
Il
value of R.
Go to steP 2.
=
15798433,
If we fo11o{ this algorithn for N
M as folLowsi
M = 5 6 6 8 3 2 , w e o b t a i n t h e s u c c e s s i v ev a L u e s o f
M'
M=
M'
M'
M'
MM=
566832
493969
72863
56791
16072
857s
?4 9 7
M = 1.078
M = 10Zg
M = 49
In this
significant
case ue execute steP 2 only nine times, e
inprovenent over AlSorith:r 1.
The phenorrrenon !,,hicl! we observe hete oecurs often in
an'l
Algorithn 1 is sinPle, streiglttforiirald,
algorithns,
2
4enler' ,Algoaitho
solves the problem io an inefficient
diffibut the cost is. additional
is fiuch mote efficient
Thls tradeoff bet{een sinpLjc:
culty in understanding it.
frequently folces the
of algorithns
ity and efficiency
alSotithtn ilesiSner to nale a decision on the subject of
priorities.
Exercis€3
1.
Modlfy nonalgorlthn 2'to nake it 4n algodthn.
2,
D€tefinln€ $hsther €ach of tho foltoring er' algorlthDs or non_
Por eech nolldlSorithn,' find tlls rule or rules it
algorithns.
it 4s an etgolltlt
violat€s end
"er{ri!s
(e) Hol{ to Prace 6 telePhone call.
1.
2.
Pick uP the t.caj.v6r.
Listen for a dial tone.
Dial th'o nutiber.
4. Conduct the conversation.
(b) Hoy t6 find a uoril ln a dlctioirary or deter'lin€ that it is
3,
not listed.
1. Turn to anY iage.
2. If {ord at the toP left
3.
4.
5,
6.
7.
8.
of the Pag' occuts alphab6_
tically afte! ths deslfsal vrord, go to step 4'
Turn ahead 10 psgss End !o to st.p 2.
Tufn back 2 Peg€s.
'
If $ord et the !o! rllilft is $ofore the desholl wofd,
go to step 3.
Scan Page fol desirid rcrd.
If it is found' lrrite a definitiotr'
rr
If it is not foEdJ Iftite, "not in dictionaly
(c) Ho'{ t o f i l l
a ditch with sand.
t.
2 . Start shoveling sand itrto the d i t c h 5.
If
go to step 1.
you rim out of satrd, go get
Ithen ditch
is full,
stop.
td) Hos a doctor heals a patient.
1 . Learn about patient's probten.
2 . Consider the slrptons.
3 . Initiate
a treatnent.
Exanine and test
5 . If patient
patient.
is cured, then
the b i 1 1 ,
3, FLOWCHART
LANG1JAGE
In
lle next ask how we s h o u l d e x p r e s s a l g o r i t h n s .
o t h e r w o r d s , i s t h e r e a convenien! language for connruni_
cat ing en slgo?ithrn fron one person to anothef or flotl
a person to a cornputeT?
e have used above in coflIiunicating
Algorithns L and 2 is English' vhich is very aPpropriate
because it i5 understood by e reasonably large subset of
EnSlish has two
the people vith whon we cotlmunicate.
disadvanteges, however. First, it i5 anbiguous as far as
The language
neaning is concerned, and therefore, even a carefully
worded algorithn cen suffer from the anbiguity of the
langtrage. Second, English is not an appropriate language
f o r c o n u n u n i c a t i n gu i t h c o n P u t e r s , s i n c e i t i s t o o c o r n p l i cated for them to understand,
$rould aPPear then, that a computer programning
language nay be an answer to our dilenrna. PTograrrning
l a n g u a g e s a r e , o f n e c e s s i t y , u n a n b j . g u o u s ,a n d a r e
And indeed one of our
understandable to the conputer.
goals is to express algorithns in this fotn so that the
It
But peoPle have difficonputer can solve the problen.
directly
in prograrnning
culty expressing algorithns
-6-
languages.
For this
reason we develop an internediate
language between English and the progranning language,
which se call rlaichart Langucse.
The expression of an algorithm in Flowchart
L a n g u a g ec o n s i s t s o f t h e r u l e s o f t h e a l g o r i t h n r r i t t e n
in abbrevialed English and pictured graphically in
"boxcs." These boxes are connected by arrows which
indicate the sequencing of the steps. Wewill use this
Flowchart Language to express all of our algorithns,
There are five different
kinds of boxes that
used in representing algorithms.
are
1. Terninel box
T e r n r i n e lb o x e s a r e u s e d t o i d e n t i f y t h e s t a r t i n g
p o i n t a n d s t o p p i n g p o i n t o f a n d l g o r i t h m . T h e yv i 1 1
always contain either lhe word STARTor the word STOP.
2, Procesing box
The work of the algorithn is specified in processing
boxes, It contains an English st atenent which describes
the action that is to be taken.
-7-
3. Input box
Each input box
rhose valrJes are to
nanes of variables
from a known source
For exanple, the box
represents the obtaining of tro values
N and the second M.
the first
ca11ed
4. Output box
Like an input box, each output box contains the
The values of these variab les are
nanes of variables,
For exarlp1e, the box
t o b e d i s p l a y e d i n s o r n ef o r n .
inilicates that the current value of X is to be displayed.
5 . D e c is i o n b o x
E a c h d e c i s i o n box contains a question !,hich can be
a n s w e r e dy e s o T n o , I f t h e a n s e r i s t r y e s , r r t h e " y e 5 , '
path is taken fron t h e b o x . I f t h e a n s w e r i s " n o , " t h e
"no" path is taken.
A s a n e x a m p l e , A l g o r i t h m I i n F l o w c h a r t L a n g u a g ei s
shovn belorv.
Set ]( to the smaller
of N and l'l
X divide both
N and M?
Subtract
fronr K
N,M,K
r-rt
l
Nanes that are used in an algorithn to represent
nunerical values and whose values nay change during the
'lhree
execution of the algorithn, are cal1ea ,aviables.
It is
variables, N, M, and K, are used in AlSorithn 1,
easier to understand uhat an algorithnL does if there is
someexplanation of the neanings of the variables included
For exanple, for Algorithn l, our
with the algorlthn.
variable descriptions r,ould be as fo11o{s:
Nane
Descriptions
N,M
The tlro Siven nunbers.
A counter used in searching for the
It will
g r e a t e s t c o n r n o nd i v i s o r .
c o n t a i n t h e g r e a t e s t c o n m o nd i v i s o r
K
li/hen the algorithn
terrninates,
Setting a variabLe to the value of another variable
or to the result of sone arithnelic explession is such a
c o n r n o na l g o r i t h n s t e p t h a t a s p e c i a l s y n b o l , t h e l e f t
lor exanple,
pointing arrovr, is used to represent it'
A-B
This notation cen
neans rrset A to the value of 8."
also be used to represent the inclenenting or decrenenting
The step ''add 1 to X" is given by
of valiab1es.
X+x+1
Using this new synbol and the v4riable
w6 can now festate Algorithn 1.
descriptions,
Given two nunbers'
ALgorithn 1 _ Second Version.
find their gfeatest connon divisor'
N and M'
Variables
Nane
N,M
(
Description
The tvro given nunbers ,
A counter used to search for the gresteS
1 ! v i l 1 c o n t a i r the
connon divisor.
g r " e a t e s t c o n m o nd i v j s o r
algorithn terrninates.
-10_
khen !he
divi.de both
N,M,K
Exercisss
3 . l{fite algorlthn 2ln the Flor{chert Lsnguags.
4 . Follo$ the algolithn describ€d in th€ forrouing flouchart
and givs the rgsulting output rhen lhs input valu€ is 5.
Nane
Variables
Descriptj.ons
N
I
SLun
The sum of the first
-11-
N integers,
su,t+sun+l
I+I+1
SOLVINGSTEPS
PROBLEM
Now that ],Jehave the concePt of an algorithn snd the
flowchart language available, we ale ready to lealn how
to use these tools in soLving problerns. It would be
sinple if we could Put the statenent of a problen lnto a
Unfor solving it
rnachine and get out an algorithn
no such nachine has ever been discovered
fortunately,
P r o b l e n s o l v i n g i s a c c o f l t p L i s h e do n l y t h r o u g h c a r e f u l w o r k :
b e F o r et h e a l g o r i t h " r i s c o n s t r u c t e d , d e t a j l e d P l a n n i n g a n d
analysis must occuri alter the algorithm is construcfed'
\2-
extenslve testing nust take place to verify
does indeed solve the probten.
that
it
In this section ll/e outline a step by-step procedure
that is useful in the construction of algorithrns which
solye problens. You night call this an algorithn for
constlucting
algorithns.
This process consists of
seven steps which are described belor,J,
l.
P r e c i s e . I yd e f i n e t h e p r o b t e n .
At this step, the probten solver deternines what
the problen is.
This step, in practice, is usuatty
quj.te difficult.
In nany courses we ate not concerned
with this step since the problens are precisely fornulated by the textbook author or the instructor,
An
p
a
r
t
inportant
of this step is deternining exactty what
forn the output of the problen shoutd have.
2. Identify
the inputs to the probtem.
A t t h i s s t e p y o u s s k , , , W h a ta r e t h e p e r t i n e n t f a c t s
l h a t d r e g i v e n i n t h i s p r o b l e r n ? ' ,T h e a n s e r q , i 1 1 d e p e n d
on what is available and $hat is needed. One inportant
aspect of this task is deternining the appropriate form
for the input.
3. Identify
the outputs of the probtenr.
Here you determine the results that are desireal. By
considering the result of step t, you should be able to
detefirine
hat is needed and in r.vhat forn.
4. Construct an algorithrn for the solution,
This is the key step in the process aDd one which
can cause the nost trouble.
Too nany problen-solvers
try !o skip this step or conbine it with the next in an
effort to obtain a solution quickly.
This is a situation
r , / h e r eh a s t e r e a l l y d o e s n a k e v r a s t e : t i n e i n v e s t e d i n
careful
fornulation
here can save nuch more tirne at steps
6 and 7.
-15-
__
5. Inplentent the algorirhrn for the sotution
I n c o n p u t e r :p r o b l e m s o l v i n g , t h i s s t e p i s k n o w n a s
progranrring. If step 4 is done carefully,
it can be
carried out in a straightforvard Nay once the basics of
a progranning language are nastefed.
6 . T e s t r h e p r o ( . e d L , cL o n s t r J c r e Ji n s t e p 4 .
Once the inplenentation is complete, we test the
procedure using inputs for which the correct outputs are
known, and conpare the results with our expectations.
If they differ,
then the existence of an error has been
discovered.
T h e r e i s a t e n p t a t i o n t o a s s u m et h e a l g o r i t h n
is correct and rush through this step. As you gain nore
e x p e r i e n c e N i t h c o f i r p u t e rp l o b l e n s o l v i n g , y o u \ 1 ' i t I l e a r n
(probably the hard way) that you should never assune anything is correct.
That kind of skeptical attitude makes
for the bes! testing.
7. Locate and correct errors uncovered by testing
back to step 6.
and go
Errors nay originate
at step 4 or step 5. Usually
those {hich originate at step 5 are fairly easy to detect
and correct because they require sone ninor modification
to the program. Errors which originate at step 4 are
nuch moredilficult.
Sucherrors nay require you to
c o n p l e E e l y r e t h i n k y o u r a l g o r i t h r a n d , i n s o - 1 ec a s e s ,
discard all you have done and start over. Again, a care
job at step 4 can avoid this weste.
AN EXA]VIPLE
L e t ' s F o 1 1 o rl.h, i s p r o c e j s r h r o u g h I o r a s i m p l e
problem. The problen is to read a set of nunbers and
deternine how nany are posltive and hofl nany are negative.
l.
Precise fonnulation - The problen as stated above
leaves out sone necessary infornation.
First, !,ha! are
we to do with zeros? Should they count as positive,
,74
negative, or not a! all?
Secondly, how ,r,i11l'e
know Uhen vre have all of the numbers?
We can solve both of these problens at once by
saying a zero will not be counted as positive or negative
but rather a zero will signify the end of rhe data.
Therefore, our more precise forrulation of the problen
now reads as fo11ows:
I
I
Read a set of nunbers until a zero is encountered and count lhe nunber of posltive and
negat ive nur0bers read.
2" Inputs - The inputs will be the given set of nunbers,
all non zero, followed by a zero. Note that any input
not cndinS with a zero is invalid for this problen,
3. output - The output of our problem consists of two
n u n b e r s , t h e n u r n b e ro f p o s i t i v e v e l u e s e n d t h e
nunber of negative values,
4. Construction of an algorithn - Our flowchart language
is a useful tool here and we can nicely fornulate our
s o1 u ! i o n a s f o l l o v r s :
Alsorithn
2. Count the nunber of positive
values in a data set - Version L
-15-
and negative
Count the nunber of
negative and the nunber
o f p o si t i v e v a l u e s
o f n e g a ti v e a n d
p o sl t l v e v a l u € s
This solution algorithm, though ccrtainly correct,
too little detail to be of sufficient use
tion.
Therefore, we refine it.
pTovides
A l g o r i t h m 3 , C o u n r L h e n u r b e r o F p o s i t i v e and nega!rve
values in a data set - Version II.
Nane
Description
NNEG
The values input.
The nunber of negative values
The nunber of positive values
NPOS
16
START
VAL=0?
VAL >O?
NNEG+NNEG+ I
N N E GN, P O S
NP0S.NP0S+1
But as ve
This algorithn appears to be correct.
w a r n e d e a r l i e r , n e v e r a s s u m ea n y t h l n g i s c o r r e c t .
Inpleinentation ' Algorithns such as this one are
implenented tr:anslating then into a conputer prograrnning language such as |ORTMN or BASIC Since this
nodule is intended to be independent of progranning
l a n g u a g e s , v e r , r i 1 1n o t d i s c u s s t h i s s t e p i n a l g o r i t h n
developnent. If you are interested in pursuing this
fJrther. yoJ 1ay do so bv ledrning to programin an)
progranming language
6 . Testing - The above algorithn was inPlenented in a
programning language and run with the following resul
Input:
Output:
12,-s,15,-2,7,0
NNEG=1762699507
3 1 58 1
N P o S2=0 0 1 7
Obviously, thcre is sonc difficulty here. The
strategy used to check for the presence of an error
nas to use an input for which we knou what the output
should be. llhen the output obtained differed from
our expectations' ue knew there was an error, and
t h e r e f o r e w e m u s t p r : o c e e dd i r e c t l y
to step 7.
Had we been successful in generating the expected output for this particular input J rl'eshould run
a d d i t . L o n a lt c i t s u n t i l w e h a v e s a t i s f i e d o u T s e l v e s
thac the procedureis correct
7. Locate and correct errors - This phase of the problen
one which is learned
solving process is a difficult
only through experience' In this case, we notice
t h a t v a l r . r e so f N N E Ga n d N P O Sa r e q u i t e v i l d a n d a f t e r
a littte
thought ue suspec! that these two variables
values, \'hich in this
vere not given proper initial
In nany programning languages'
case should be zeros.
v a r i a b l e s l i k e N N E Ga n d N P O Sa r e n o t a u t o n a t i c a l l y s e t
In order to insure the correctness of our
to zero.
18
p r o S r a mb r en e e d t o r n c l u d e s ! e p s t o d o t h i s .
'
nodilied to include these
initialization" to zero, it tales the folloLing forn.
Algorithn 4. Count the nunber of positive
Yalues in a data set ' Version l.
and negative
Name
The values input.
NNEG
NPOS
The nunber of negative values
The nunber of positive values
NNEG*0
NP0S-0
N N E G, N P O
VAL= O?
VAL>()?
NP0S.NP0S+1
N N E G - N N E1G +
-19'
rrr6r r.1 hr ih6 .n-rp.r,..r l\hich results in
A l g o r i t h m4 . \ e m u q t r e t u r n a g a i n t o s t c p 6 f o r t e s t i n g .
Extensive testing of the inplenented version of this
a l g o r i t h n w i l l r e v e a l n o f u r t h e r e r r : o r s . W h e nw e h a v e
tested enough to satisfy
of the algorithn,
ourselves with the correctness
we accept it as providing the solution
l , v eh a v e n o w o u t l i n e d a b a s i c p r o c e d u r e f o r s o l v i n g
a p r o b l e n . T h i s p r o c e d u r ec a n b e p u t i r , t h e f o r - o f "
flowchart as vre11.
20-
Follo
through the first
four of the seven problen solving steps
with the folloBing probtems:
5. Pur three numbersinto nAr-descending order.
calcutate the nean of a set of nunbers
7 . Input a lositivc integer and conpute the sumof atl
fron one to the integer input.
integers
8 . I n p u t a n a m o u n tA , a n d a n i n t e r e s t r a t e I .
Cohputerhe lrincipal
resulting if A dollars are invested for a given time perio.l
ith lnterest rate I percent per tire perlod.
9. Input A and I as in 8, and N, the nunber of time periods.
Conpute rhe principal resuttlrg if A doliars are invested for
N tine periods ,lth interest rate I percent per tine period
c o n p o u n d e da f t e r e a c h t i m e p e r i o d .
-22
6.
l
Onepossibte sotution night be:
1.
Readthe Daterial.
2.
Iisten
L
4.
5.
2.
ANSWERS
TO EXERCISES
attentlvely
in class.
Outline the naterial.
Gets lots of sleep the night before.
Take the e)ranination.
ta) Nonargorithn because it rnay fail !o
sorve the problen.
lor exanpte, what happens if the
rlne is busy?
(b) Nonalgorith,nbecause
it nay not solve the probren.
Tf
the search begins on an even (odd)
page, then onry even
(odd) pages {irl be scanneal.
rf step 4 had read, ,,Tun
back 1 page," the procedure ould
nave been an atgorithm.
(c) Nonargorithn because it
is ambiglous. step 3 does not
exprain how to get nole sand.
(d) Nonalgorithn
because steps are out of ord6r.
If steps
e r e c h a n 8 e dr o 1 , 4 , 2 , 3 , 5 t h e n
it would be better,
A1so,
no action is specified if pati6nt
is nor curert, so the
procedure nay not teminate.
One could adit the step:
6. If patient dies, then stop
rreatnent.
3.
Exchange
and M
Divide N by M,
the renaine!
cali
4. This sitl print
N=5
sunFI5
5.
Precise fo nulatior;
Put three real nunbers into non-descendi
three nunbers in original
output:
order.
The thrce nunbers in non-descending order
Name
A,B,C
The three variables
read and placed in order
uith A the smallest and c the largest.
- 24-
Exchange B
and C
Exchange A
and B
A,B,C
6. Precise forrnulation: Read
a vatue N, folloued by N real
numberslrnd calculate the nean
of the
Input: N and N real values.
Output: The meanof the N real
vatues.
--
Algorithn:
Nme
Description
Tbe nuber
K
of values read.
The counter fron t to N.
The sun of the vatues read.
vatue
The values xhose nean is computed.
26
j8 . Precise fomulation:
and an lnterest
principal
Inlut:
Given a principal
ahount A in dollars
rate I in percent per tinre period,
conpute
at the end of one tine period.
Principal anount A and interest
rate I.
Output: Pdncipar after one tine period.
Algorithn:
Variables
Descrlptlon
!!!9
The anount of beginning principar.
I
The aflount of principat
at the end of
the time period.
9. Precise fonrulation:
Given a principal
ar'ount A
rate I in percent per tin'e leriod, and a numberof time
peliods N, comlute the lrincipar at the end of N
interest
Irput:
Principal anount A, interest
rate I, and
output: Principal after N tjme leriods.
-28,
Nane
Description
The amount of beginning princilal.
rate ln Percent
1
The interest
N
The nuiber of tinre Perio.ls.
A coNter fron I to N.
K
after
The princiPal
K tiite
prir+prin+prin x 1/100
K+K+t
-29,
periods'
MODELEXAM
i.
Detemine thich of tbe fo11o{lng are algorithns and uhich are
nonalgorithns. For those that are nonalgorithns, ei!1ain uhv'
(a)
(b)
Hou to shovel snot off
1
Get a shovel.
2.
Removea shovelfull
3.
If thele is still
4,
Stop,
of snou fron the driveuav
s n o No n t h e d r i v e w a y , g o t o s t e p 2 '
H o wt o b u Y a n e w c a r .
l2,
3.
4.
(c)
a diivewav
lind thc car You want.
Find out its Pricc
Ask You" fathcr fox the norel
B U Yt h e c a r .
H o wt o f i n d a j o b
1
2.
3_
Deterninc vhich jobs are oPen.
for the jobs You lant
Intedie!
Decidc whjch jobs lou uourd like
Get the necessary tralt1ng.
5.
2.
What output wilr
the following algorithn gcnerate?
Design an algorithm for solving the folloring
problem: Convert
length from inches to feet and inches.
'. I
D e r , n . i 5 e p r o b l e or o r e p r e c i i e l / .
(b)
The folroNing are the boxes neededfor an algoritbn to
solre lhiq ?'ollen
I:ll jn Lhel*o enpl) borer
r!
.
r
.
L_II_J
b o x e 5 . b o v e i n t o a f 1 o & c h rr t
Use each box exactly once.
to solve the
8.
r.
languaSealgoritnm
SOLU'I'I
ONS 10 MOnl]- t)iAll
(cl
( b l 'fhis does not solve the prohlcn
reccive tllc noney by asking
(c)
Thc stcps fc
out of sequcncc.
2
3
2
4
5
'Ihe prcbleD could norc precisely say:
Convert a length fron lnches to feet and inches Nhere
the nunber of feet is integer and as large as possjble
(1,)
lnput box slould contain "inches"output bo:( should contain i'feet,
31-
inchesr'.
hes>12
inches+inchss_I2
Download