Upload
others
View
15
Download
0
Embed Size (px)
Citation preview
CO
DE
EAT SLEEP
A N I N T R O D U C T I O N T O
C R E A T I V E P R O B L E M S O L V I N G
V . A N T O N S P R A U L
T H I N K L I K EA P R O G R A M M E RA P R O G R A M M E R
T H I N K L I K E
CO
DE
EAT SLEEPR E W I R ER E W I R E
Y O U R B R A I NY O U R B R A I N
$34.95 ($36.95 CDN)
www.nostarch.com
TH E F I N EST I N G E E K E NTE RTA I N M E NT™
“ I L I E F LAT .”
Th is book uses RepKover — a durab le b ind ing that won’t snap shut. SHELVE IN:
PROGRAMM
ING/GENERAL
• Master more advanced programming tools like recursionand dynamic memory
• Organize your thoughts and develop strategies to tackleparticular types of problems
Although the book’s examples are written in C++, thecreative problem-solving concepts they illustrate go beyondany particular language; in fact, they often reach outside the realm of computer science. As the most skillful programmers know, writing great code is a creative art—and the firststep in creating your masterpiece is learning to Think Like a Programmer.
distillation of the techniques he has used and honed over
A B O U T T H E A U T H O R
V. Anton Spraul has taught introductory programming andcomputer science for more than 15 years. This book is a
many one-on-one sessions with struggling programmers.He is also the author of Computer Science Made Simple.
The real challenge of programming isn’t learning alanguage’s syntax—it’s learning to creatively solve problems so you can build something great.
In this one-of-a-kind text, author V. Anton Spraul breaks down the ways that programmers solve problems andteaches you what other introductory books often ignore:how to Think Like a Programmer. Each chapter tackles
and recursion, and open-ended exercises throughouta single programming concept, like classes, pointers,
challenge you to apply your knowledge.
You’ll also learn how to:
them easier to solve• Split problems into discrete components to make
• Make the most of code reuse with functions, classes,and libraries
• Pick the perfect data structure for a particular job
CO
DE EAT SLEEP
TH
INK
LIK
E A
PR
OG
RA
MM
ER
TH
INK
LIK
E A
PR
OG
RA
MM
ER
C O N T E N T S I N D E T A I L
ACKNOWLEDGMENTS xi
INTRODUCTION xiiiAbout This Book ...................................................................................................... xv
Prerequisites .............................................................................................. xvChosen Topics ........................................................................................... xvProgramming Style .................................................................................... xviExercises .................................................................................................. xviWhy C++? ...............................................................................................xvii
1STRATEGIES FOR PROBLEM SOLVING 1Classic Puzzles ........................................................................................................ 2
The Fox, the Goose, and the Corn ................................................................ 3Problem: How to Cross the River? ....................................................................... 3Sliding Tile Puzzles ...................................................................................... 7Problem: The Sliding Eight .................................................................................. 7Problem: The Sliding Five ................................................................................... 8Sudoku .................................................................................................... 11Problem: Completing a Sudoku Square ............................................................. 11The Quarrasi Lock ..................................................................................... 13Problem: Opening the Alien Lock ...................................................................... 13
General Problem-Solving Techniques ........................................................................ 15Always Have a Plan .................................................................................. 16Restate the Problem ................................................................................... 17Divide the Problem .................................................................................... 17Start with What You Know ......................................................................... 18Reduce the Problem ................................................................................... 19Look for Analogies .................................................................................... 20Experiment ............................................................................................... 20Don’t Get Frustrated .................................................................................. 21
Exercises ............................................................................................................... 22
2PURE PUZZLES 25Review of C++ Used in This Chapter ........................................................................ 26Output Patterns ...................................................................................................... 26
Problem: Half of a Square ................................................................................ 26Problem: A Square (Half of a Square Reduction) ............................................... 27Problem: A Line (Half of a Square Further Reduction) ......................................... 27Problem: Count Down by Counting Up .............................................................. 28Problem: A Sideways Triangle .......................................................................... 29
Input Processing ..................................................................................................... 31Problem: Luhn Checksum Validation ................................................................. 31Breaking Down the Problem ....................................................................... 33
Think Like a Programmer©2012, V. Anton Spraul
viii Contents in Detai l
Problem: Convert Character Digit to Integer ...................................................... 35Problem: Luhn Checksum Validation, Fixed Length ............................................ 36Problem: Simple Checksum Validation, Fixed Length ......................................... 36Problem: Positive or Negative .......................................................................... 39Putting the Pieces Together ......................................................................... 39
Tracking State ........................................................................................................ 41Problem: Decode a Message ............................................................................ 41Problem: Reading a Number with Three or Four Digits ...................................... 45Problem: Reading a Number with Three or Four Digits, Further Simplified .......... 46
Conclusion ............................................................................................................ 53Exercises ............................................................................................................... 53
3SOLVING PROBLEMS WITH ARRAYS 55Review of Array Fundamentals ................................................................................. 56
Store ....................................................................................................... 56Copy ....................................................................................................... 57Retrieval and Search ................................................................................. 57Sort ........................................................................................................ 59Compute Statistics ..................................................................................... 61
Solving Problems with Arrays ................................................................................... 62Problem: Finding the Mode .............................................................................. 62Refactoring ............................................................................................... 65
Arrays of Fixed Data .............................................................................................. 67Non-scalar Arrays .................................................................................................. 69Multidimensional Arrays .......................................................................................... 71Deciding When to Use Arrays ................................................................................. 74Exercises ............................................................................................................... 78
4SOLVING PROBLEMS WITH POINTERS AND DYNAMIC MEMORY 81Review of Pointer Fundamentals ............................................................................... 82Benefits of Pointers ................................................................................................. 83
Runtime-Sized Data Structures ..................................................................... 83Resizable Data Structures ........................................................................... 83Memory Sharing ....................................................................................... 84
When to Use Pointers ............................................................................................. 84Memory Matters ..................................................................................................... 85
The Stack and the Heap ............................................................................. 86Memory Size ............................................................................................ 88Lifetime .................................................................................................... 90
Solving Pointer Problems ......................................................................................... 91Variable-Length Strings ............................................................................... 91Problem: Variable-Length String Manipulation .................................................. 91Linked Lists ............................................................................................. 101Problem: Tracking an Unknown Quantity of Student Records ........................... 101
Conclusion and Next Steps ................................................................................... 108Exercises ............................................................................................................. 109
Think Like a Programmer©2012, V. Anton Spraul
Contents in Detai l ix
5SOLVING PROBLEMS WITH CLASSES 111Review of Class Fundamentals ............................................................................... 112Goals of Class Use ............................................................................................... 113
Encapsulation ......................................................................................... 114Code Reuse ............................................................................................ 114Dividing the Problem ............................................................................... 115Information Hiding .................................................................................. 115Readability ............................................................................................. 117Expressiveness ........................................................................................ 117
Building a Simple Class ........................................................................................ 118Problem: Class Roster .................................................................................... 118The Basic Class Framework ...................................................................... 119Support Methods ..................................................................................... 122
Classes with Dynamic Data ................................................................................... 125Problem: Tracking an Unknown Quantity of Student Records ........................... 126Adding a Node ...................................................................................... 128Rearranging the List ................................................................................. 130Destructor ............................................................................................... 133Deep Copy ............................................................................................. 134The Big Picture for Classes with Dynamic Memory ....................................... 139
Mistakes to Avoid ................................................................................................ 140The Fake Class ........................................................................................ 140Single-Taskers ......................................................................................... 141
Exercises ............................................................................................................. 141
6SOLVING PROBLEMS WITH RECURSION 143Review of Recursion Fundamentals ......................................................................... 144Head and Tail Recursion ....................................................................................... 144
Problem: How Many Parrots? ......................................................................... 144Approach 1 ............................................................................................ 145Approach 2 ............................................................................................ 146Problem: Who’s Our Best Customer? .............................................................. 148Approach 1 ............................................................................................ 149Approach 2 ............................................................................................ 151
The Big Recursive Idea .......................................................................................... 152Problem: Computing the Sum of an Array of Integers ...................................... 153
Common Mistakes ................................................................................................ 155Too Many Parameters .............................................................................. 155Global Variables ..................................................................................... 156
Applying Recursion to Dynamic Data Structures ....................................................... 158Recursion and Linked Lists ........................................................................ 158Problem: Counting Negative Numbers in a Singly Linked List ........................... 159Recursion and Binary Trees ...................................................................... 160Problem: Find the Largest Value in a Binary Tree ............................................. 162
Wrapper Functions ............................................................................................... 163Problem: Find the Number of Leaves in a Binary Tree ...................................... 163
When to Choose Recursion ................................................................................... 165Arguments Against Recursion .................................................................... 166
Think Like a Programmer©2012, V. Anton Spraul
x Contents in Detai l
Problem: Display a Linked List in Order .......................................................... 168Problem: Display a Linked List in Reverse Order .............................................. 168
Exercises ............................................................................................................. 170
7SOLVING PROBLEMS WITH CODE REUSE 171Good Reuse and Bad Reuse .................................................................................. 172Review of Component Fundamentals ...................................................................... 173
Code Block ............................................................................................ 173Algorithms .............................................................................................. 173Patterns .................................................................................................. 174Abstract Data Types ................................................................................ 175Libraries ................................................................................................. 175
Building Component Knowledge ............................................................................ 176Exploratory Learning ................................................................................ 176Problem: The First Student .............................................................................. 177As-Needed Learning ................................................................................ 180Problem: Efficient Traversal ............................................................................ 180
Choosing a Component Type ................................................................................ 188Component Choice in Action .................................................................... 189Problem: Sorting Some, Leaving Others Alone ................................................ 189Comparing the Results ............................................................................. 193
Exercises ............................................................................................................. 193
8THINKING LIKE A PROGRAMMER 195Creating Your Own Master Plan ............................................................................ 196
Playing to Your Strengths and Weaknesses ................................................ 196Putting the Master Plan Together ............................................................... 202
Tackling Any Problem ........................................................................................... 203Problem: Cheating at Hangman ..................................................................... 204Finding a Way to Cheat .......................................................................... 205Required Operations for Cheating at Hangman .......................................... 206Initial Design .......................................................................................... 208Initial Coding .......................................................................................... 210Analysis of Initial Results .......................................................................... 217The Art of Problem Solving ....................................................................... 218
Learning New Programming Skills .......................................................................... 219New Languages ...................................................................................... 219New Skills for a Language You Already Know ............................................ 222New Libraries ......................................................................................... 223Take a Class ........................................................................................... 223
Conclusion .......................................................................................................... 224Exercises ............................................................................................................. 225
INDEX 227
Think Like a Programmer©2012, V. Anton Spraul