Print words entered, but backwards. Solving Problems Recursively. Faster exponentiation. Exponentiation

Similar documents
Fundamentals of Recursion. Solving Problems Recursively. Recursive example. Recursive example

Data Structures And Algorithms

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Recursion. Chapter 7

Recursive Definitions

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Recursion(int day){return Recursion(day += 1);} Comp Sci 1575 Data Structures. Recursive design. Convert loops to recursion

Lecture 24 Tao Wang 1

Semantics of while loop. From Selection to Repetition. ReverseString as a function. Print a string backwards

Recursion. Recursion [Bono] 1

1.7 Recursion. Department of CSE

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

Chapter 5: Recursion

Understanding Recursion

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Recursion. Chapter 5

CSE 2123 Recursion. Jeremy Morris

Recursion (Rosen, 6 th edition, Section 4.3, 4.4)


Recursion Chapter 3.5

CmpSci 187: Programming with Data Structures Spring 2015

CSC212. Data Structure. Lecture 12 Reasoning about Recursion. Instructor: George Wolberg Department of Computer Science City College of New York

Chapter 5: Recursion

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

CSci 1113, Fall 2015 Lab Exercise 7 (Week 8): Arrays! Strings! Recursion! Oh my!

Tools for algorithms and programs. From practice to theory and back again. On to sorting: Selection Sort. To code or not to code, that is the

CMPSCI 187: Programming With Data Structures. Lecture #15: Thinking Recursively David Mix Barrington 10 October 2012

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

Solving problems by recursion

Sorting & Searching (and a Tower)

Recursion. So, just as you are allowed to call function B from within function A, you are ALSO allowed to call function A from within function A!

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

Recursion. Thinking Recursively. Tracing the Recursive Definition of List. CMPT 126: Lecture 10. Recursion

Recursion. Chapter 11. Chapter 11 1

= otherwise W-4 W-1. Overview. CSE 142 Computer Programming I. Overview. Factorial Function

Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank

1 Recursion. 2 Recursive Algorithms. 2.1 Example: The Dictionary Search Problem. CSci 235 Software Design and Analysis II Introduction to Recursion

Dynamic Programming Algorithms

Recursion. Jordi Cortadella Department of Computer Science

A Useful Case. A Fruitful Application of Recursion: n-queen problem

Recursion. Recursion is: Recursion splits a problem:

Chapter 5: Recursion. Objectives

n 1 x i = xn 1 x 1. i= (2n 1) = n 2.

6.001 Notes: Section 4.1

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

CSE11 Lecture 20 Fall 2013 Recursion

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?

Data Structures Lecture 3 Order Notation and Recursion

CSC-140 Assignment 4

Odds and Ends. Think about doing research Programming grading. Assignment 3 due Tuesday

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

Summary. csci 210: Data Structures Recursion. Recursive algorithms. Recursion. Topics READING:

csci 210: Data Structures Recursion

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series.

Fun facts about recursion

CMPSCI 187: Programming With Data Structures. Lecture #16: Thinking About Recursion David Mix Barrington 12 October 2012

UNIVERSITY REGULATIONS

Lecture 8 Recursion. The Mirrors

Complexity, Induction, and Recurrence Relations. CSE 373 Help Session 4/7/2016

APCS-AB: Java. Recursion in Java December 12, week14 1

Unit #3: Recursion, Induction, and Loop Invariants

In either case, remember to delete each array that you allocate.

Recursive Thinking. Chapter 8: Recursion. Recursive Definitions. Recursion. Java Software Solutions for AP* Computer Science A 2nd Edition

An algorithm is a sequence of instructions that one must perform in order to solve a wellformulated

CS221: Algorithms and Data Structures Lecture #11 Recursion vs. Iteration Proofs about Recursion/Iteration

Chapter 15: Recursion

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

Reading 8 : Recursion

What is recursion? Recursion. Recursive message() modified. How can a function call itself? contains a reference to itself. Week 10. Gaddis:

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

CSC 273 Data Structures

Declaring a 2D Array

For loops, nested loops and scopes. Jordi Cortadella Department of Computer Science

Dynamic Programming I

Recursion. COMS W1007 Introduction to Computer Science. Christopher Conway 26 June 2003

Chapter 2. Question 2 Write a box trace of the function given in Checkpoint Question 1. We trace the function with 4 as its argument (see next page).

Chapter 17 - Notes Recursion

Unit #2: Recursion, Induction, and Loop Invariants

Recursion. ! When the initial copy finishes executing, it returns to the part of the program that made the initial call to the function.

Analyzing Complexity of Lists

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.

Pace University. Fundamental Concepts of CS121 1

Vectors. A Computer Science Tapestry 8.1

6/4/12. Recursive void Methods. Chapter 11. Vertical Numbers. Vertical Numbers. Vertical Numbers. Algorithm for Vertical Numbers

Chapter 10 - Notes Applications of Arrays

CSCE 2014 Final Exam Spring Version A

Solutions to Problem 1 of Homework 3 (10 (+6) Points)

Learning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution

Unit 10: Sorting/Searching/Recursion

Hanoi, Counting and Sierpinski s triangle Infinite complexity in finite area

Chapter 13 Recursion. Chapter Objectives

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems. COMP Week 8 & 9 1

CSCI-1200 Data Structures Fall 2017 Lecture 7 Order Notation & Basic Recursion

The Art of Recursion: Problem Set 10

How to work a workbook

Transcription:

Solving Problems Recursively 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 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 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 Need both concepts: call on the clone and use the result Print words entered, but backwards 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.1 A Computer Science Tapestry 10.2 Exponentiation 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); What about an iterative version? Faster exponentiation How many recursive calls are made to computer 2 1024? 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; What about an iterative version of this function? A Computer Science Tapestry 10.3 A Computer Science Tapestry 10.4

Blob Counting: Recursion at Work Blob counting is similar to what s called Flood Fill, the method used to fill in an outline with a color (use the paintcan in many drawing programs to fill in) Possible to do this iteratively, but hard to get right Simple recursive solution 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 Counting blobs, the first slide prompt> blobs enter row col size 10 50 # pixels on: between 1 and 500: 200 +--------------------------------------------------+ * * * * * * *** * **** * * * * *** ** ** * * * * * * * * *** * * *** * * * * * * * * ** * ** ** * ** * * * *** * * * * ***** *** * * ** ** * * * * * * * ** * *** * *** * * * *** * ** * * * * * ** * * ** * * * * *** ** * **** * * ** **** * *** * * ** ** * * * ** **** ** * * ** * +--------------------------------------------------+ 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 10.5 A Computer Science Tapestry 10.6 Identifying Larger Blobs blob size (0 to exit) between 0 and 50: 10...1......111......1......11......111...2......1...2......111...33...2......1...3...222.22......11..3333...222......33.3333... # 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 Identifying smaller blobs blob size (0 to exit) between 0 and 50: 5...1...2......1.1...222......111...333.2...4......33..22...444...5......33333.222...6...44...55......2...6...444...555......222...77...6...4......8...2...7...666.66....8888...22..7777...666... 88..8...77.7777... # blobs = 8 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 10.7 A Computer Science Tapestry 10.8

Issues that arise in studying code 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? 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 We ll study these concepts in more depth, a minimal understanding is needed to work on blobs.cpp 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 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 10.9 A Computer Science Tapestry 10.10 Conceptual Details of BlobFill 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? 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 Non-recursive member function takes care of looking for blobsign, then filling/counting/unfilling blobs How is unfill/uncount managed? Saving blobs In current version of Blobs::FindBlobs the blobs are counted What changes if we want to store the blobs that are found? How can clients access the found blobs? What is a blob, does it have state? Behavior? What happens when a new minimal blob size is specified? Why are the Blob class declaration, member function implementations, and main function in one file? Advantages in using? blobs.h, blobs.cpp, doblobs.cpp? How does Makefile or IDE take care of managing multiple file projects/programs? A Computer Science Tapestry 10.11 A Computer Science Tapestry 10.12

Back to Recursion Recursive functions have two key attributes There is a base case, sometimes called the exit case, which does not make a recursive call See print reversed, exponentiation, factorial for examples All other cases 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 Example: sequential search in a vector If first element is search key, done and return Otherwise look in the rest of the vector How can we recurse on rest of vector? Classic examples of recursion 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.13 A Computer Science Tapestry 10.14 Fibonacci: Don t do this recursively Towers of Hanoi long RecFib(int n) // precondition: 0 <= n // postcondition: returns the n-th Fibonacci number if (0 == n 1 == n) return 1; return RecFib(n-1) + RecFib(n-2); How many clones/calls to compute F(5)? 4 3 2 2 1 1 0 1 1 0 5 2 How many calls of F(1)? How many total calls? See recfib2.cpp for caching code 3 1 0 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; 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.15 A Computer Science Tapestry 10.16

What s better: recursion/iteration? 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 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 Static function variable: maintain value over all function calls Local variables constructed each time function called Fixing recursive Fibonacci: recfib2.cpp long RecFib(int n) // precondition: 0 <= n <= 30 // postcondition: returns the n-th Fibonacci number static tvector<int> storage(31,0); if (0 == n 1 == n) return 1; if (storage[n]!= 0) return storage[n]; storage[n] = RecFib(n-1) + RecFib(n-2); return storage[n]; 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 10.17 A Computer Science Tapestry 10.18 Thinking recursively Problem: find the largest element in a vector Iteratively: loop, remember largest seen so far Recursive: find largest in [1..n), the compare to 0 th element double Max(const tvector<double>& 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)? Recursive Max double RecMax(const tvector<double>& 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]; return maxafter; What is base case (conceptually)? We can use RecMax to implement Max as follows return RecMax(a,0); A Computer Science Tapestry 10.19 A Computer Science Tapestry 10.20

Recognizing recursion: void Change(tvector<int>& 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); What is base case? (no recursive calls) What happens before recursive call made? How is recursive call closer to the base case? More recursion recognition int Value(const tvector<int>& 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; What is base case, what value is returned? How is progress towards base case realized? How is recursive value used to return a value? What if a is vector of doubles, does anything change? A Computer Science Tapestry 10.21 A Computer Science Tapestry 10.22 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 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; Why did recursive version need the helper function? Where does initialization happen in recursion? How is helper function related to idea above? Is one of these easier to understand? What about developing rather than recognizing? A Computer Science Tapestry 10.23 A Computer Science Tapestry 10.24