A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems.

Slides:



Advertisements
Similar presentations
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
Advertisements

Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
Recursion Chapter 7. Spring 2010CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
19-Aug-15 Simple Recursive Algorithms. 2 A short list of categories Algorithm types we will consider include: Simple recursive algorithms Backtracking.
Recursion Chapter 5.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
1 Storage Classes, Scope, and Recursion Lecture 6.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
CompSci 100E 10.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
CPS 100, Spring From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
CompSci 100 Prog Design and Analysis II Sept 16, 2010 Prof. Rodger CompSci 100, Fall
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Chapter 8 Recursion Modified.
CompSci 100E 12.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
CompSci 100e 6.1 Hashing: Log ( ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a.
Compsci 100, Fall From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
CompSci Review of Recursion with Big-Oh  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
CPS Today’s topics Programming Recursion Copyrights, patents, and digital media Reading Great Ideas, p Brookshear, Section Online.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Recursion Fundamentals of Recursion l Base case (aka exit case)  Simple case that can be solved with no further computation  Does not make a recursive.
CPS Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved simply.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit ä Allows many complex problems.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
A Computer Science Tapestry 1 Announcements l Please complete the Course Evaluations l Final exam on December 24, 2015, Thursday ä at 16:00 (more info.
CPS Today’s topics Programming Recursion Invariants Reading Great Ideas, p Brookshear, Section Upcoming Copyrights, patents, and.
Recursion Chapter 2 Objectives Upon completion you will be able to:
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Recursion,
Recursion Powerful Tool
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Recursion Version 1.0.
Recursion Topic 5.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion: The Mirrors
Plan for the Week Review for Midterm Source code provided
Solving Problems Recursively
Recursion Chapter 12.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 12 Recursion (methods calling themselves)
Writing Methods AP Computer Science A.
Announcements Final Exam on August 19th Saturday at 16:00.
Announcements Final Exam on December 25th Monday at 16:00.
Announcements HW3 grades will be announced this week
Solving Problems Recursively
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Solving Problems Recursively
Presentation transcript:

A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved simply  Elegance and understanding in code often leads to better programs: easier to modify, extend, verify (and sometimes more efficient!! See expotest.cpp)  Sometimes recursion isn’t appropriate, when it’s bad it can be very bad---every tool requires knowledge and experience in how to use it l The basic idea is to get help solving a problem from coworkers (clones) who work and act like you do  Ask clone to solve a simpler but similar problem  Use clone’s result to put together your answer l Need both concepts: call on the clone and use the result

A Computer Science Tapestry 10.2 Fundamentals of Recursion l Base case (aka exit case)  Simple case that can be solved with no further computation  Does not make a recursive call l Reduction step (aka Inductive hypothesis)  Reduce the problem to another smaller one of the same structure  Make a recursive call, with some parameter or other measure that decreases or moves towards the base case Ensure that sequence of calls eventually reaches the base case “Measure” can be tricky, but usually it’s straightforward l The Leap of Faith !  If it works for the reduction step is correct and there is proper handling of the base case, the recursion is correct. l What row are you in?

A Computer Science Tapestry 10.3 Recursive example void WriteBinary(int n) // Writes the binary representation // of n to cout. { if (n < 0) { cout << "-"; WriteBinary(-n); } else if (n < 2) cout << n; else { WriteBinary(n/2); cout << n % 2; } n:

A Computer Science Tapestry 10.4 Recursive example void mystery(int n) { if (n <= 1) cout << n; else { mystery(n/2); cout << “, ” << n; } n:

A Computer Science Tapestry 10.5 Classic examples of recursion l For some reason, computer science uses these examples:  Factorial: we can use a loop or recursion (see facttest.cpp ), is this an issue?  Fibonacci numbers: 1, 1, 2, 3, 5, 8, 13, 21, … F(n) = F(n-1) + F(n-2), why isn’t this enough? What’s needed? Classic example of bad recursion, to compute F(6), the sixth Fibonacci number, we must compute F(5) and F(4). What do we do to compute F(5)? Why is this a problem?  Towers of Hanoi N disks on one of three pegs, transfer all disks to another peg, never put a disk on a smaller one, only on larger Every solution takes “forever” when N, number of disks, is large

A Computer Science Tapestry 10.6 Towers of Hanoi l The origins of the problem/puzzle may be in the far east  Move n disks from one peg to another in a set of three void Move(int from, int to, int aux, int numDisks) // pre: numDisks on peg # from, // move to peg # to // post: disks moved from peg 'from‘ // to peg 'to' via 'aux' { if (numDisks == 1) { cout << "move " << from << " to " << to << endl; } else { Move (from,aux,to, numDisks - 1); Move (from,to,aux, 1); Move (aux,to,from, numDisks - 1); } Peg#1 #2 #3

A Computer Science Tapestry 10.7 Fibonacci: Don’t do this recursively long RecFib(int n) // precondition: 0 <= n // postcondition: returns the n-th Fibonacci number { if (0 == n || 1 == n) { return 1; } else { return RecFib(n-1) + RecFib(n-2); } l How many clones/calls to compute F(5)? How many calls of F(1)? How many total calls? See recfib2.cpp for caching code

A Computer Science Tapestry 10.8 Print words entered, but backwards l Can use a vector, store all the words and print in reverse order  The vector is probably the best approach, but recursion works too void PrintReversed() { string word; if (cin >> word) // reading succeeded? { PrintReversed(); // print the rest reversed cout << word << endl; // then print the word } int main() { PrintReversed(); } The function PrintReversed reads a word, prints the word only after the clones finish printing in reverse order  Each clone has its own version of the code, its own word variable

A Computer Science Tapestry 10.9 Exponentiation l Computing x n means multiplying n numbers (or does it?)  What’s the easiest value of n to compute x n ?  If you want to multiply only once, what can you ask a clone? double Power(double x, int n) // post: returns x^n { if (n == 0) { return 1.0; } return x * Power(x, n-1); } l What about an iterative version?

A Computer Science Tapestry Faster exponentiation l How many recursive calls are made to computer ?  How many multiplies on each call? Is this better? double Power(double x, int n) // post: returns x^n { if (n == 0) { return 1.0; } double semi = Power(x, n/2); if (n % 2 == 0) { return semi*semi; } return x * semi * semi; } l What about an iterative version of this function?

A Computer Science Tapestry Recursive and Iterative log powers l In the program expotest.cpp we calculate x n using log(n) multiplications (basically). We do this both iteratively and recursively using BigInt variables  We saw the iterative code in Chapter 5 with doubles  BigInt has overloaded operators so these values work like ints and doubles  We use the CTimer class to time the difference in using these functions (ctimer.h) l The recursive version is faster, sometimes much faster  Using doubles we wouldn’t notice a difference  Artifact of algorithm? Can we “fix the problem”?  Natural version of both in programs, optimizing tough.

A Computer Science Tapestry What’s better: recursion/iteration? l There’s no single answer, many factors contribute  Ease of developing code assuming other factors ok  Efficiency (runtime or space) can matter, but don’t worry about efficiency unless you know you have to l In some examples, like Fibonacci numbers, recursive solution does extra work, we’d like to avoid the extra work  Iterative solution is efficient  The recursive inefficiency of “extra work” can be fixed if we remember intermediate solutions: static variables l Static function variable: maintain value over all function calls  Local variables constructed each time function called

A Computer Science Tapestry Fixing recursive Fibonacci: recfib2.cpp long RecFib(int n) // precondition: 0 <= n <= 30 // postcondition: returns the n-th Fibonacci number { static tvector storage(31,0); if (0 == n || 1 == n) return 1; else if (storage[n] != 0) return storage[n]; else { storage[n] = RecFib(n-1) + RecFib(n-2); return storage[n]; } l What does storage do? Why initialize to all zeros?  Static variables initialized first time function called  Maintain values over calls, not reset or re-initialized

A Computer Science Tapestry Thinking recursively l Problem: find the largest element in a vector  Iteratively: loop, remember largest seen so far  Recursive: find largest in [1..n), then compare to 0 th element double Max(const tvector & a) // pre: a contains a.size() elements, 0 < a.size() // post: return maximal element of a { int k; double max = a[0]; for(k=0; k < a.size(); k++) { if (max < a[k]) max = a[k]; } return max; }  In a recursive version what is base case, what is measure of problem size that decreases (towards base case)?

A Computer Science Tapestry Recursive Max double RecMax(const tvector & a, int first) // pre: a contains a.size() elements, 0 < a.size() // first < a.size() // post: return maximal element a[first..size()-1] { if (first == a.size()-1) // last element, done { return a[first]; } double maxAfter = RecMax(a,first+1); if (maxAfter < a[first]) return a[first]; else return maxAfter; } l What is base case (conceptually)? We can use RecMax to implement Max as follows return RecMax(a,0);

A Computer Science Tapestry Recognizing recursion: void Change(tvector & a, int first, int last) // post: a is changed { if (first < last) { int temp = a[first]; // swap a[first], a[last] a[first] = a[last]; a[last] = temp; Change(a, first+1, last-1); } // original call (why?): Change(a, 0, a.size()-1); l What is base case? (no recursive calls) l What happens before recursive call made? l How is recursive call closer to the base case?

A Computer Science Tapestry More recursion recognition int Value(const tvector & a, int index) // pre: ?? // post: a value is returned { if (index < a.size()) { return a[index] + Value(a,index+1); } return 0; } // original call: cout << Value(a,0) << endl; l What is base case, what value is returned? l How is progress towards base case realized? l How is recursive value used to return a value? l What if a is vector of doubles, does anything change?

A Computer Science Tapestry One more recognition void Something(int n, int& rev) // post: rev has some value based on n { if (n != 0) { rev = (rev*10) + (n % 10); Something(n/10, rev); } int Number(int n) { int value = 0; Something(n,value); return value; } What is returned by Number(13) ? Number(1234) ?  This is a tail recursive function, last statement recursive  Can turn tail recursive functions into loops very easily

A Computer Science Tapestry Non-recursive version int Number(int n) // post: return reverse of n, e.g., 4231 for n==1234 { int rev = 0; // rev is reverse of n's digits so far while (n != 0) { rev = (rev * 10) + n % 10; n /= 10; } l Why did recursive version need the helper function?  Where does initialization happen in recursion?  How is helper function related to idea above? l Is one of these easier to understand? l What about developing rather than recognizing?

A Computer Science Tapestry Blob Counting: Recursion at Work l Blob counting is similar to what’s called Flood Fill, the method used to fill in an outline with a color (use the paint- can in many drawing programs to fill in)  Possible to do this iteratively, but hard to get right  Simple recursive solution l Suppose a slide is viewed under a microscope  Count images on the slide, or blobs in a gel, or …  Erase noise and make the blobs more visible To write the program we’ll use a class CharBitMap which represents images using characters  The program blobs.cpp and class Blobs are essential too

A Computer Science Tapestry Counting blobs, the first slide prompt> blobs enter row col size # pixels on: between 1 and 500: | * * * * * * *** * **** * * | | * *** * * *** * * * * * * * * **| | * ** ** * ** * * * *** * * | | * * ***** *** * * ** ** * | |* * *** * ** * * * * * ** | |* * ** * * * * *** ** * | | **** * * ** **** * *** * * **| |** * * * ** **** ** * * ** *| l How many blobs are there? Blobs are connected horizontally and vertically, suppose a minimum of 10 cells in a blob  What if blob size changes?

A Computer Science Tapestry Identifying Larger Blobs blob size (0 to exit) between 0 and 50: # blobs = 3 The class Blobs makes a copy of the CharBitMap and then counts blobs in the copy, by erasing noisy data (essentially)  In identifying blobs, too-small blobs are counted, then uncounted by erasing them

A Computer Science Tapestry Identifying smaller blobs blob size (0 to exit) between 0 and 50: # blobs = 8 l What might be a problem if there are more than nine blobs?  Issues in looking at code: how do language features get in the way of understanding the code?  How can we track blobs, e.g., find the largest blob?

A Computer Science Tapestry Issues that arise in studying code l What does static mean, values defined in Blobs?  Class-wide values rather than stored once per object  All Blob variables would share PIXEL_OFF, unlike myBlobCount which is different in every object  When is static useful? l What is the class tmatrix?  Two-dimensional vector, use a[0][1] instead of a[0]  First index is the row, second index is the column l We’ll study these concepts in more depth, a minimal understanding is needed to work on blobs.cpp

A Computer Science Tapestry Recursive helper functions Client programs use Blobs::FindBlobs to find blobs of a given size in a CharBitMap object  This is a recursive function, private data is often needed/used in recursive member function parameters  Use a helper function, not accessible to client code, use recursion to implement member function l To find a blob, look at every pixel, if a pixel is part of a blob, identify the entire blob by sending out recursive clones/scouts  Each clone reports back the number of pixels it counts  Each clone “colors” the blob with an identifying mark  The mark is used to avoid duplicate (unending) work

A Computer Science Tapestry Conceptual Details of BlobFill l Once a blob pixel is found, four recursive clones are “sent out” looking horizontally and vertically, reporting pixel count  How are pixel counts processed by clone-sender?  What if all the clones ultimately report a blob that’s small? l In checking horizontal/vertical neighbors what happens if there aren’t four neighbors? Is this a potential problem?  Who checks for valid pixel coordinates, or pixel color?  Two options: don’t make the call, don’t process the call l Non-recursive member function takes care of looking for blobsign, then filling/counting/unfilling blobs  How is unfill/uncount managed?