0% found this document useful (0 votes)
77 views

How To Solve It by Computer

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
77 views

How To Solve It by Computer

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 463
PRENTICE-HALL SCI ENCE R.G. Dromey How fo Solve it by Computer C.A.R. HOARE SERIES EDITOR HOW TO SOLVE IT BY COMPUTER R. G. DROMEY Department of Computing Science The University of Wollongong ENGLEWOOD CLIFFS, NEW JERSEY LONDON NEW DELHI SINGAPUKE «= SYUNEY = GUKYU)— TURUNTU WELLINGTON Library of Congress Cataloging in Publication Daa DROMEY,R.G, — 1946- How 10 Soive it by Computer, Bibliography: p. Includes index 1. Mathematics—-Daia processing 2. Problem solving—Data processing 2, teetronic aigitat computers—rrogramming 1. Title. QA76.95.D76 S194 B1-19164 ISBN 0.13-433095.9 AACR? ISBN 0-13-434001-9 (phk.) British Library Cataloging in Publication Data DROMEY, R.G. How to Solve it by Computer. SU8 —QAS.58 ISBN 0-13-433995.9 ISBN 0-13.434001-9 (PBK) © 1982 by PRENTICE-HALL INTERNATIONAL, INC., London © 1982 by PRENTICE-HALL INC., Englewood Cliffs, NJ. 07632 All rights reserved. ‘No part of this publication may be reproduced, without the prior permission of the publisher TSRN Q-13-uaz99s-4 ISBN O-13-434001~95 {PBK} PRENTICE HALL INTERNATIONAL, INC, London PRENTICE-HALL OF AUSTRALIA PTY. LTD. Sydney PRENTICE-HALL CANADA. INC., Toronto PRENTICE-HALL OF INDIA PRIVATE LTD., New Delhi PRENTICE-HALL OF JAPAN, INC,, Tokyo PRENTICE-HALL OF SOUTHEAST ASIA PTE., TD., Singapore PRENTICE-HALL, INC,, Englewood Clif, New Jersey WHITEHALL BOOKS LIMITED, Wellimgion, New Zealand Printed in the United States of Amecica 10987654321 This book is dedicated to George Polya We learn most when We have to invent Piaget CONTENTS PREFACE xili ACKNOWLEDGEMENTS xx INTRODUCTION TO COMPLITER PROBLEM-SOLVING 1 Introduction 1 2 ‘The Problem-solving Aspect 3 3 Top-down Design 7 4 Implementation of Algorithms 14 6 7 i L 1. 1 LS Progiam Ve ion 19 4.6 The Efficiency of Algorithms 29 1.7. The Analysis of Algorithms 33 Bibliography 39 FUNDAMENTAL ALGORITHMS 42 Introduction 42 Algorithm 2.1 Exchanging the Values of Two Variables 43 Algorithm 2,2. Counting 47 Algorithm 2.3 Summation of a Set of Numbers 51 Algorithm 2.4 Factorial Computation 56 Algorithm 2.5. Sine Function Computation 60 Algorithm 2.6 Generation of the Fibonacci Sequence 64 Algorithm 2.7 Reversing the Digits of an Integer 69 Algorithm 2.8 Base Conversion 74 Algorithm 2.9 Character to Number Conversion 80 Bibliography 84 x CONTENTS 3 FACTORING METHODS: 85 intraduction 85 Algorithm 3.1 Finding the Square Root of a Number. 86 Algorithm 3.2. The Smallest Divisor of an Integer 92 Algorithm 3.3. The Greatest Common Divisor of Two inegers 97 Algorithm 3.4 Generating Prime Numbers 105 Algorithm 3.5 Computing the Prime Factors of an Integer 116 Algorithm 3.6 Generation of Pseudo-random Numbers 120 Algorithm 3.7. Raising a Number to a Large Power 124 Algorithm 3.8 Computing the nth Fibonacei Number 132 Bibliography 138 ARRAY TECHNIQUES 139 is 129 ithm 4.1 Aray Order Reversal 140 Algorithm 4.2 Array Counting or Histogramming 144 Algorithm 4.3 Finding the Maximum Number ina Set 147 Algorithm 4.4 Removal of Duplicates from an Ordered Alg Algorithm 4.5 joning an Array 156 Algorithm 4.6 Finding the kth Smailest Element 166 Algorithm 4.7 Longest Monotone Subsequence 174 Bibliography 180 MERGING, SORTING AND SEARCHING 181 Introduction 181 Algorithm 5.1 The Two-way Merge 182 Algorithm 5.2 Sorting by Selection 192 Algorithm 5.3 Sorting by Exchange 198 Algorithm 5.4 Sorting by Insertion 204 Algorithm 5.5 Sorting by Diminishing Increment 209 Algorithm 5.6 Sorting by Partitioning 216 Algorithm 5.7. Binary Search 227 Algorithm 5. Hash Scarching 237 Bibliography 246 TEXT PROCESSING AND PATTERN SEARCHING 248 Introduction 248 Algorithm 6.1 Text Line Length Adjustment 249 Algorithm 6.2 Left and Right Justification of Text 256 Algorithm 6.3 Keyword Searching in Text 267 Algorithm 6.4 Text Line Editing 274 Algorithm 6.5 Linear Pattern Search 282 Algorithm 6.6 Sublinear Pattern Search 293 Bibliography 303 CONTENTS. xi DYNAMIC DATA STRUCTURE ALGORITHMS 304 Introduction 304 Algorithm 7.1 Stuck Operations 306 Algorithm 7.2. Queue Addition and Deletion 314 Algorithm 7.3 Linked List Search 375 Algorithm 7.4 Linked List Insertion and Deletion 331 Algorithm 7.5 Binary Tree Search 342 Algorithm 7.6 Binary Tree Insertion and Deletion 349 Bibliography 366 RECURSIVE ALGORITHMS 367 Introduction 367 Algorithm 81 Binary Tree Traversal 373 m8.2 Re st 383 Algorithm 83 Towers of anal Problem 391 Algorithm 8.4 Sample Generation 404 Algorithm 8.5 Combination Generation 414 Algorithm 8.6 Permutation Generation 422 graphy 433 INDEX = =—s_ «435, PREFACE The inspiration for this book has come from the classic work of Polya on general and mathematical problem-solving. As in mathematics, many beginners in computing science stumble not because they have difficulty with learning a programming language but rathcr because they are ill- prepared to handle the problem-solving aspects of the discipline. Unfortu- nately, the school system seems to concentrate on training people to answer questions and remember facts but not to really solve problems, in response to this situation, it was felt there was a definite need for a book written in the spirit of Polya’s work, but translated into the computing science context. Much of Polya's work is relevant in the new context but, with computing problems, because of their general requirements for itera- tive or recursive solutions. another dimension is added to the problem- solving process. If we can develop problem-solving skills and couple them with top- down design principles, we are well on the way to becoming competent at algorithm design and program implementation. Emphasis in the book has been placed on presenting strategies that we might employ to “discover” efficient, well-structured computer algorithms. Throughout, a conscious effort has been made to convey something of the flavor of either a personal dialogue or an instructor-student dialogue that might take place in the solution of a problem. This style of presentation coupled with a carefully chosen set of examples, should make the book attractive to a wide range of readers. The student embarking on a first course in Pascal should find that the material provides a lot of useful guidance in separating the tasks of learning how to develop computer aigorithms and of then impiementing thems in a programming language like Pascal. Too often. the end is confused with the xii xiv PREFACE means. A good way to work with the book for self-study is to read only as much as you need to get started on a problem. Then, when you have developed your own solution, compare it with the one given and consciously reflect on the strategies that were helpful or hindersome in tackling the problem. As Yohe! has rightly pointed out “programming [computer probiem-soiving] is an art andj as in aii art forms, each individual must develop a style which seems natural and genuine.” Instructors should also find the style of presentation very useful as lecture material as it can be used to provide the cues for a balanced amount of instructor-class dialogue. The author has found students receptive and responsive to lectures presented in this style. The home-computer hobbyist wishing to develop his or her problem- solving and programming skills without any formal lectures should find the completeness of presentation of the various algorithms a very valuable suppiement to any introductory Pascai text. itis hoped that even some of the more advanced algorithms have been rendered more accessible to beginners, than is usually the case. The material presented, although elementary for the most part, con- tains some examples and topics which should be of sufficient interest and challenge to spark, in the beginning student, the enthusiasm for computing that we so often see in students who have begun to master their subject. Readers are urged not to accept passively the algorithm solutions given. Wherever it is possible and practical, the reader should strive for his or her own simpier or betier aigoritims. As aiways, the limitations of space have meant that some topics and examples of importance have either had to be omitted or limited in scope. To some degree the discussions and supplemen- tary problems that accompany each algorithm are intended to compensate for this. The problem sets have been carefully designed to test, reinforce, and extend the reader's understanding of the strategies and concepts presented. Readers are therefore strongly urged to attempt a considerable proportion of these problems. Each chapter starts off with a discussion of relatively simple, graded examples, that are usually related in some fairly direct way. Towards the middle and end of each chapter, the examples are somewhat more involved. A good way to work with the book is to only consider the more fundamental algorithms in cach chapter at a first reading. This should allow the necessary build-up of background needed to study in detail some of the more advanced algorithms at a later stage. The chapters are approximately ordered in increasing order of concep- tual difficulty as usually experienced by students, The first chapter intro- + J.M. Yohe, “An overview of programming practices”, Comp. Surv., 6 221-46 (1974) PREFACE xv duces the core aspects of computer problem-solving and algorithm design. Ata first reading the last half of the chapter caa be skimmed through. Where possible, the ideas are reinforced with examples, The problem-solving dis- cussion tries to come to grips with the sort of things we can do when we are stuck with a problem. The important topic of program verification is pre- semed in a way that shouid de reiatively easy for the reader to grasp and apply at least to simple algorithms. Examples are used to convey something of the flavor of a probabilistic analysis of an algorithm. ‘The second chapter concentrates on developing the skill for formulating iterative solutions to problems—a skill we are likely to have had little experience with before an encounter with computers. Several problems are also considered which should allow us to come to a practical understanding of how computers represent and manipulate information. The problem of conversion from one representation to another is also addressed. The aigorithms in this chapter are aii treated as if we were faced with the task of discovering them for the first time. Since our aimis to foster skill in computer problem-solving, this method of presentation would seem to be appropriate from a pedagogical standpoint. Algorithms in the other chapters are also discussed in this style. In the third chapter, we consider a number of problems that have their origin in number theory. These algorithms require an extension of the iterative techniques developed in the first chapter. Because of their nature, most of these problems can be solved in a number of ways and can differ widciy in their computational cost. Confronting the question of efficiency adds an extra dimension to the problem-solving process. We set out to “discover” these algorithms as if for the first time. Atray-processing algorithms are considered in detail in Chapter 4. Facility with the use of arrays needs to be developed as soon as we have understood and are able to use iteration in the development of algorithms. Arrays, when coupled with iteration, provide us with a very powerful means of performing computations on collections of data that share some common attribute. Strategies for the efficient processing of array information raise some interesting problem-solving issues. The algorithms discussed are intended to address at least some of the more important of these issues. ‘Once arrays and iteration have been covered, we have the necessary tools to consider merging, sorting and searching algorithms. These topics are discussed in Chapter 5. The need to organize and subsequently efficiently search large volumes of information is central in computing science. A number of the most well-known internal sorting and searching algorithms are considered. An attempt is made to provide the settings that would allow us to “discover” these algorithms. ‘The sixth chapter on texi and suring processing represents a diversion from the earlier emphasis on “numeric” computing. The nature and organ- xvi PREFACE ization of character information raises some important new problem-solving issues, The demands for efficiency once again lead to the consideration of some interesting algorithms that are very different from those reviewed in earlier chapters. The algorithms in this chapter emphasize the need to develop the skill of recognizing the essentials of a problem without being confused or misied by extraneous det. ing’ some of these algorithms provides an interesting test-bed for us to apply some of the problem-solving skills we should have absorbed after covering the first five chapters. Chapter 7 is devoted to the fundamental algorithms for maintaining and searching the primary dynamic data structures (i.e. stacks, queues, lists, and binary trees). The issues in this chapter arise mostly at the implementation level and with the use of pointers, In the final chapter, the topic of recursion is introduced. A recursive call is presented as an extension of the conventional subprocedure cali. The simplest form of recursion, linear recursion, is only briefly treated because the view is taken that there are almost always simple iterative schemes that can be found for performing what amounts to linear recursion. Furthermore, linear recursion does little to cither convey anything of the power of recur- sion or to really deepen our understanding of the mechanism. The same cannot usually be said for problems involving either binary recursion or the more general non-linear recursion, Algorithms that belong to both these classes are discussed in detail, with special emphasis being placed on recog- nizing their underlying simijarities and deepening our undersianding of recursion mechanisms. As a concluding remark about the book, if the author were to hope that this work may achieve anything, it would be that it stimulated students and others to embark on a journey of discovering things for themselves! A SUGGESTION FOR INSTRUCTORS “...any idea or problem or body of knowledge can be presented in a form simple enough so that any particular Iearner can understand it in a recognizable form.” —Bruner. In comparison with most other human intellectual activities, computing is i its infancy despite the progress we seem to have made in such a short time. great in our rapidly changing world, we have not had time to sit back and A SUGGESTION FOR INSTRUCTORS | xvii reflect on the best way to convey the “computing concept” on a wide scale. In time, computing will mature and cyolve as a well-understood discipline with clear and well-defined methods for introducing the subject to begin- ners—but that is in the future. For the present, because we are not in this happy situation, it is most prudent to look to other mature disciplines for guidance on how we shouid introduce computing to beginners, Assuming we want to have the highest possible success rate in introducing computing to students (a situation which clearly at present does not prevail) and that we want to teach computing on the widest possible scale, then the most obvious discipline to turn to is that of learning to read and write. Educators have mastered the process of teaching people to read and write to the extent that these skills are able to be transmitted on a very wide scale. efficiently, and with a very high rate of success. Putting aside the various methods within the learning-to-tead-and-write discipline we see that there are some fundamentai principies acknowledged by aii methods that are highly relevant to teaching computing. In teaching people to read and write a very substantial time (years in fact) is devoted to reading. Only after such preparation is it considered appropriate that they should attempt to write stories or essays, or books, etc. In fact, even before people attempt to learn to read they undergo several yeurs of listening to language, speaking, and being “read to”. Clearly, in learning a language, the ultimate goal is to be able to verbalize and write fluently in that language. Similarly in computing the goal is to be able to program (or design and impiement algorithms) effectively. in earning to read and write it has long been recognized that reading is easier and that it must precede writing by a considerable margin of time to allow the assimila- tion of enough models and constructs of text to make writing possible. In teaching computing we seem to have overlooked or neglected what corresponds to the reading stage in the process of learning to read and write. To put it strongly, asking people to design and write programs early on in their computing experience islike expecting that they be able to competently write essays before they have learned to read or even to write short sen- tences—it is expecting just too much of a lot of people. It also probably explains why many otherwise very able people just don’t get started in computing. What we are therefore proposing is that in teaching computing we should draw as much as we can from the learning-to-read-and-write analogy. This means that we must be able to provide the beginning student with his or her “reading experience” in computing before embarking on the more difficult computer problem-solving tasks which require considerably more creative effort, discipline, and technical skill. Ai this puini ii is imporiant iv secugnize thai ihe “reading expeticuce” cannot be gained by sitting down with a book of programs and attempting to xviii PREFACE “read” them. The problem with this approach is that program instructions as written on a picce of paper are a static representation of a computer algorithm. As such they do not very fluently convey anything of the dynamic aspect of computer algorithms and programs. It can be argued that it is important to have a clear and in-depth understanding of the dynamic character of programs before attempting algorithm design and program implementation. What is needed isa practical and economical method of giving students their “reading experience” in computing. To gain this experience the students need to “see” programs written in a high level language executing. Traditionally, all the student sees is the output printed on the terminal or line printer and prompts by the program when it requires input from the terminal. This level of “seeing” a program execute is unsatisfactory for beginners because it conveys very little about the program’s flow of control or about the effects of individual and groups of program starements. What we need is much more expiicit demon- strations of what is happening in a program that causes it to produce the outputs that it does. A far more transparent way to do this is to place before the student on a terminal the text of the program being executed and then to trace the execution on the displayed program while at the same time dynam- ically updating on the screen the changes in program variables as they are made and related to steps in the displayed program. This dynamic method of studying algorithms can greatly assist the student in acquiring a level of understanding necessary to design and implement his or her own algorithms. ‘The faciiities and sofiware woois needed to adequately demonstrate execution of a program in this way are relatively economical to provide. All that is needed is a terminal with cursor addressing facilities and a small set of software tools (several hundsed lines of code) that can be inserted into the program being studied to make its execution “visible” on the screen. Only ‘one procedure call per statement of the program being studied is needed to operate itin a visible mode (this software is available from the author). The display software is transparent to the user. The appropriate tools allow us to see a program execute in single-step mode while monitoring the changes in variables as they are dynamically displayed on the screen. The student can cause the program to execute the next statement at each stage by simply pressing a single key (e.g. the RETURN) on the terminal. As an cxample, the screen layout for “visible” execution of a selection sorting procedure in Pascal is as illustrated in Fig. 1. The next statement to be executed at each stage is tracked by having an arrow that can be moved from statement to statement on the procedure text displayed on the screen. A more complete description of the software is given elsewhere.t + R. G. Dromey, Before Programming—On Teaching Introductory Contputing, Technical Report No. 81/6, Dept. of Computing Science, University of Wolton- gong (1981). A SUGGESTION POR INSTRUCTORS xix procedure selectionsort(a:nelements; n:integer); var i {index for sorted part}, j {index for unsorted part}, P {position of minimum}. min {minimum in unsorted part): integer: begin for i= 1 ton-t do 1 | af 12 begin ‘min += afi}; pmis de} 2 falls] 4 for j:= i+ tondo if off] < min then begin 1 lap):) 12 min = ai jf; ann aan a 7 Ch == ap] 8 | min: 4 aw: 12 4 56 67 9 23 45 Fig. 1 Screen layout far visible program execution, The cause-and-effect nature of what is displayed when executing prog- sunny in this manner (automatic singie-step mode) can accomplisa a number of things. (1) Most importantly, it provides a good understanding of the dynamic nature of algorithms—an essential prerequisite if students are to later design and implement their own algorithms. (2). Iegives a deep insight into the basic laws of composition of computer algorithms (sequence, selection, iteration, and modularity), (3) Itis a useful vehicle for helping students to learn various programming constructs. Actually observing constructs being used within different programming contexts and linking these constructs to changes in the values of variables and conditions gives the student the necessary concrete demonstrations that will enable him or her to master the use of these constructs. (4) Itconveys in a very vivid fashion the workings of a particular algorithm For exainple, the selection sort algorithm when visibly executed con- veys the difficult concept of how we can have one loop executing within another loop. It also highlights the difference between subscripted variables and subscripis. xx PREFACE (5) It also provides an ideal tool for teaching students debugging tech- niques. That is, programs with logical bugs can be implemented and the student asked to diagnose the problem after studying the program in visible execution mode. Visible program execution has the added advantage of being ideally suited for use in the lecture room, classroom, or library, Most terminals have the capability of video output which can be connected to a video recorder. Using these facilities it is very easy and cheap to monitor and record the visible program execution of a variety of programs for later use on video monitors in the classrouin or library. This gives us a leaching aid far superior to handwritten blackboard examples when lecturing about algorithms in the classroom. We have recorded and used a number of programs in this way We cai i fc tude of piogiain execution a step further by making it more active with respect to the student. At each step in the program's execution we can ask the student to supply the appropriate value of the variable or condition etc. How this works can be best illustrated by referring back to the figure. The arrow is indicating that the 7 statement (ie. p:= j)is the next one to be executed. What the software can do is move the cursor to the “‘p”’ box on the screen and indicate to the student that he must supply the appropriate value for p (in this case 2) betore the program will continue. If the user enters the wrong value the word ERROR will flash the user to again try to enter the proper p vatue. If the user gets it wrong twice the software flashes VALUE in the p-hox and then supplies the user with the correct valuc, switches from interactive to automatic single step mode, and moves to the next program statement to be executed. Using a visible program in interactive single-step mode can in a very direct way reinforce the student's comprchcnsion of how a program really works and what individual program statements accomplish, At the same time it can give the student very positive and direct feedback when he gets something wrong. ‘What we are therefore advocating is that students be given considerable exposure ta visible “program-reading” in both the modes described as a preparatory step to considering the problem-solving aspect of computer algorithm design. Exposure to visible program execution (VPE) should be accompanied by a study of the basic laws of composition of computer algorithms (sequence, selection, itcration and modularity) including how these laws of form relate to the way programs are executed. Concurrently, a study should also be made of the syntax of the programming language being ACKNOWLEDGEMENTS The inspiration for the approach taken in this book grew out of an admira- tion for George Polya’s classic works on problem-solving. During the summer and autumn of 1980, I had the pleasure of spending a number of afternoons chatting with Professor and Mrs. Polya. k and that of the pioneers of the discipline ‘The influence of Polya’s of computing science, E. stra, Floyd, C. A. R. Hoare, D. E. Knuth. andN, Wirth. is freely acknowledged. There is also a strong influence of Jeff Rohl’s work in the last chapter on recursion. Isincerely appreciate the guidance and encouragement given to me by Professor Hoare. Henry Hirschberg. Ron Decent. and my reviewers. [am also grateful to the University of Wollongong and Stanford Uni- versity for the use of their facilities. A number of people have generously given helpful comments and support during the preparation of the manuscript. I would particularly like to thank Tom Bailey, Miranda Baker, Harold Brown, Bruce Buchanan, Ann Cartwright. John Farmer. Tony Guttman, Joan Hutchinson. Leanne Koring, Donald Knuth, Rosalyn Maloney, Richard Miller, Ross Nealon, Jurg Nievergell, Richard Patis, Ian Pirie, Juris Reinfelds, Tom Richards, Michael Shepanksi, Stanley Smerin and Natesa Sridharan and my students at Wol- longong. The understanding and encouragement throughout this whole project that I have received from my wife Aziza is deeply appreciated. Finally, I wish to extend my deepest gratitude to Bronwyn James for her loyalty and untiring and able suppor in ihe preparation aud typing of the manuscript. xxi Chapter 1 INTRODUCTION TO COMPUTER PROBLEM-SOLVING 1.1 INTRODUCTION Computer problem-solving can be summed up in one word—it is demand- ing! It is an intricate process requiring much thonght, careful planning logical precision, persistence, and attention to detail. At the same time it can be a challenging, exciting, and satisfying experience with considerable room for personal creativity and eypressinn Tf eamputer problem-solving is approached in this spitit then the chances of success are greatly amplified. In the discussion which follows in this introductory chapter we will attempt to lay the foundations for our study of computer problem-solving 1.1.1 Programs and algorithms The vehicle for the computer solution to a problem is a set of explicit and unambiguous instructions expressed in a programming language. This set of instructions is called a program. A program may also be thought of as an algorithm expressed in a programming language. An algorithm therefore corresponds to a solution to a problem that is independent of any program- ming language. ‘To obtain the computer solution to a problem once we have the pro- gram we usually have to supply the program with input or data. The program then takes this input and manipulates it according to its instructions and eventually produces an output which represents the computer solution to the problem. The realization of the computer output is but the last step in a very long chain of events that have led up to the computer solution to the problem. 2 COMPUTER PROBLEM-SOLVING CHAP. Our goal in this work is to study in depth the process of algorithm design with particular emphasis on the problem-solving aspcets of the task. There are many definitions of an algorithm. The following definition is appropriate in computing science. An algorithm consists of a set of explicit and unam- biguous finite steps which, when carried out for a given set of initial condi- tions, produce the corresponding output and terminate in a finite time. 1.1.2. Requirements for solving problems by computer From time to time in our everyday activities, we employ algorithms to solve problems. For example, to look up someone’s telephone number in a tele- phone directory we need to employ an algorithm. Tasks such as this are usually performed automatically without any thought to the complex under- iying mechanism needed to effectively conduct the search. it therefore comes as somewhat of a surprise to us when developing computer algorithms that the solution must be specified with such logical precision and in such detail, After studying even a small sample of computer problems it soon becomes obvious that the conscious depth of understanding needed to design effective computer algorithms is far greater than we are likely to encounter in almost any other problem-solving situation. Let us reflect for a moment on the telephone directory look-up prob- lem. A telephone directory quite often contains hundreds of thousands of names and telephone numbers yet we have iittie troubie finding the desired telephone number we are seeking. We might therefore ask why do we have so little difficulty with a problem of seemingly great size? The answer is simple. We quite naturally take advantage of the order in the directory to quickly climinate large sections of the list and home in on the desired name and number. We would never contemplate looking up the telephone number of J. R. Nash by starting at page 1 and examining each name in turn until we finally come to Nash’s name and telephone number. Nor are we likely to contemplate looking up the name of the person whose number is 2987533. ‘To conduct such a search, there is no way in which we can take advantage of the order in the directory and so we are faced with the prospect of doing a number-by-number search starting at page 1. If, on the other hand, we had a list of telephone numbers and names ordered by telephone number rather than name, the task would be straightforward. What these examples serve to emphasize is the important influence of the data organization on the perfor- mance of algorithms. Only when a data structure is symbiotically linked with an algorithm can we expect high performance. Before considering these and other aspects of algorithm design we need to address the topic of problem- soiving in some deta SEC. 12 THE PROBLEM-SOLVING ASPECT 3 1.2 THE PROBLEM-SOLVING ASPECT It iy widely recognized that problen-solving is a creative process which largely defies systematization and mechanization. This may not sound very Teo bal during their schooling, acquire at least a modest set of probiem- solving skills which they may or may not be aware of. Even if one is not naturally skilled at problem-solving there are a number of steps that can be taken to raise the level of one's performance. itis not implied or intended that the suggestions in what follows are in any way a recipe for problem-solving. The plain fact of the matter is that there is no universat method. Different strategies appear to work for different people. Within this context, then, where can we begin to say anything useful computer problem-solving is about understanding. 1.2.1 Problem definition phase Success in solving any problem is only possible after we have made the effort tocome to terms with or understand the problem at hand. We cannot hope to make useful progress in solving a problem until we fully understand what itis we are trying to solve. This preliminary investigation may be thought of as the prodiem definition phase. in other words, what we must do during this phase is work out what must be done rather than how to do it. That is. we must try to extract from the problem statement (which is often quite impre- cise and maybe even ambiguous) a set of precisely defined tasks. Inexperi- enced problem-solvers too often gallop ahead with how they are going to solve the problem only to find that they are either solving the wrong problem or they ate solving just a very special case of what is actually required. In short, a lot of care should be taken in working out precisely what must be done. The development of algorithms for finding the square root (algorithm 3.1) and the greatest common divisor (algorithin 3.3) are good illustrations ‘of how important it is to carefully define the problem. Then, from the definitions, we are led in a natural way to algorithm designs for these two problems. 1.2.2. Getting started on a problem ‘There are many ways to solve most problems and also many solutions to most problems, This situation docs not make the job of problem-solving easy. When confronted with many possible lines of attack it is usually 4 COMPUTER PROBLEM-SOLVING cuap.t difficult to recognize quickly which paths are likely to be fruitless and which paths may be productive. Perhaps the more common situation for people just starting to come to grips with the computer solution to problems is that they just do not have any dea where to start on the problem, even after the problem definition phase. en confronted with this situation, what can we do? A Diock often occurs at this point because people become concerned with details of the implemen- tation before they have completely understood or worked out an implementation-independent solution. The best advice here is not to be too concerned about detail. That can come later when the complexity of the problem as a whole has been brought under control. The old computer proverb! which says “the sooner you start coding your program the longer it is going to take” is usually painfully true. 1.2.3 The use of specific examples ‘A useful strategy when we are stuck is to use some props or heuristics (i.e. rules of thumb) to try to get a start with the problem. An approach that often allows us to make a start on a problem is to pick a specific example of the general problem we wish tosolve and try to work out the mechanism that will allow us to solve this particular problem (e.g. if you want to find the maximum ina set of numbers, choose a particular set of numbers and work out the mechanism for finding the maximum in this set—see for example algorithm 4.3), itis usually much easier to work out the details of a solution to a specific problem because the relationship between the mechanism and the particular problem is more clearly defined. Furthermore, a specific problem often forces us to focus on details that are not so apparent when the problem is considered abstractly. Geometrical or schematic diagrams rep- resenting certain aspects of the problem can be usefully employed in many instances (see, for example, algorithm 3.3). ‘This approach of focusing on a particular problem can often give us the foothold we need for making a start on the solution to the general problem. ‘The method should, however, not be abused. It is very easy to fall into the trap of thinking that the solution to a specific problem or a specific class-of problems is also a solution to the general problem. Sometimes this happens but we should always be very wary of making such an assumption. Ideally, the specifications for our particular problem need to be examined very carefully to try to establish whether or not the proposed algorithm can meet those requirements, If the full specifications are difficult to formulate sometimes a well-chosen set of test cases can give us a degree of i HF, Ledgard, Programming Proverbs, tiayden, Rochetie Fark, N.i., 1973.

You might also like