Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Recursion COMP 102 #33 2015T1.

Slides:



Advertisements
Similar presentations
MiniDraw Testing COMP 102 # T1
Advertisements

Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Methods COMP.
Recursion (define tell-story (lambda () (print ‘’Once upon a time there was a mountain. ‘’) (print ‘’On the mountain, there was a temple. ‘’) (print ‘’In.
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.
Recursive Functions The Fibonacci function shown previously is recursive, that is, it calls itself Each call to a recursive method results in a separate.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Topic 7 – Recursion (A Very Quick Look). CISC 105 – Topic 7 What is Recursion? A recursive function is a function that calls itself. Recursive functions.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 15 Recursive Algorithms.
Recursion CITS1001.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
20-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Recursion. Basic problem solving technique is to divide a problem into smaller sub problems These sub problems may also be divided into smaller sub problems.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Data Structures and Abstractions with Java, 4e Frank Carrano
Algorithmic Recursion. Recursion Alongside the algorithm, recursion is one of the most important and fundamental concepts in computer science as well.
Comp 245 Data Structures Recursion. What is Recursion? A problem solving concept which can be used with languages that support the dynamic allocation.
Week 5 - Monday.  What did we talk about last time?  Linked list implementations  Stacks  Queues.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Recursion COMP 102 # T1.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Recursion COMP 102 #32.
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
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.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
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.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Conditionals.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with Methods COMP.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Recursion COMP 102 # T1.
February ,  2/16: Exam 1 Makeup Papers Available  2/20: Exam 2 Review Sheet Available in Lecture  2/27: Lab 2 due by 11:59:59pm  3/2:
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Recursion COMP 103 #
Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Fields, Constructors.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Methods Calling Methods Return.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington More Recursion COMP 102 #30.
1 Recursion. 2 A process by which a function calls itself repeatedly  Either directly. X calls X  Or cyclically in a chain. X calls Y, and Y calls X.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Chapter 15 Recursion.
COMP 103 RECURSION.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Chapter 15 Recursion.
Java 4/4/2017 Recursion.
RECURSION COMP 103 Thomas Kuehne 2016-T2 Lecture 16
Recursion Chapter 10.
Lesson #6 Modular Programming and Functions.
Applied Algorithms (Lecture 17) Recursion Fall-23
Algorithm design and Analysis
Announcements Final Exam on August 19th Saturday at 16:00.
Chapter 15 Recursive Algorithms Animated Version
Unit 3 Test: Friday.
Lesson #6 Modular Programming and Functions.
Recursion Taken from notes by Dr. Neil Moore
Java Programming: Chapter 9: Recursion Second Edition
February , 2009 CSE 113 B.
Presentation transcript:

Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Recursion COMP 102 # T1

© Peter Andreae COMP :2 Outline A new control structure: Recursion Recursion Simple Recursive methods Recursive methods that return values ⇒ Understanding methods and parameters properly Very important for COMP103; not an assessed topic for COMP102 :

© Peter Andreae COMP :3 What is Recursion? Something is recursive if it is defined in terms of itself Recursion is a powerful mental tool for: Defining mathematical functions Describing complex patterns/structures Designing programs/algorithms Solving problems But isn’t that circular? There must be a non-recursive alternative (“base case”) The recursive case must be “smaller” © Lindsay Groves

© Peter Andreae COMP :4 Recursive Functions A function is recursive if it is defined in terms of itself: Factorial, iterative definition: 10! = 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 3 x 2 x 1 n! = n x n-1 x n-2 x … x 2 x 1 Factorial, recursive definition: 1! = 1 n! = n x (n-1)!, for n > 1 Fibonacci numbers: Fib(0) = 0 Fib(1) = 1 Fib(n) = Fib(n-1) + Fib(n-2), for n > 1 What’s Fib(5) ? © Lindsay Groves In both cases: There is a non-recursive ("base") case. The arguments in the recursive cases are closer to the base case.

© Peter Andreae COMP :5 Recursive Specifications of Language A Java expression can be: 〈constant 〉 〈variable 〉 〈expression 〉 〈operator 〉 〈expression 〉 ( 〈expression 〉 ) 〈methodname 〉 ( 〈expression 〉, …, 〈expression 〉 ) 〈arrayexpression 〉 [ 〈expression 〉 ] 〈expression 〉 == 〈expression 〉 etc A Java statement can be: 〈variable 〉 = 〈expression 〉 ; 〈methodname 〉 ( 〈expression 〉, …, 〈expression 〉 ) if ( 〈condition 〉 ) { 〈statement 〉 … } else { 〈 statement 〉 … } while ( 〈condition 〉 ) { 〈statement 〉 … } etc. © Lindsay Groves

© Peter Andreae COMP :6 Recursive Methods Methods can call other methods: public void drawBubbles(double x, double y, int n){ for (int i = 0; i<n; i++ ) { this.drawBubble(x, y, 10); y = y – 15; } } public void drawBubble(double x, double y, double size){ UI.setColor(Color.blue); UI.fillOval(x, y, size, size); } A method can also call itself ! Definition of drawBubbles method Calling drawBubble method Definition of drawBubble method Calling setColor & fillOval methods

© Peter Andreae COMP :7 Repetition with Recursion /** Draw a stream of n bubbles up from a point (x, y ) */ public void drawBubbles(double x, double y, int n){ // draw one bubble this.drawBubble(x, y, 10); // if there are any remaining bubbles if ( n > 1 ) { // draw them int restY = y-15; this.drawBubbles(x, restY, n-1); } }

© Peter Andreae COMP :8 More Recursion /** Draw stream of bubbles from (x,y) to the top of the screen */ public void drawBubbles2(double x, double y){ if ( y>0 ) { // Draw first bubble this.drawBubble(x, y, 10); // Draw the rest of the bubbles. int restY = y-15; this.drawBubbles2(x, y-15); } }

© Peter Andreae COMP :9 Recursion vs Iteration Iteration: break problem into sequence of the typical case identify the typical case (body) identify the increment to step to the next case identify the keep-going or stopping condition identify the initialisation Recursion: (simple) break problem into first and rest identify the first case identify the recursive call for the rest work out the arguments for the rest identify when you should do the recursive call. make sure there is a stopping case (base case) may need a wrapper method to initialise

© Peter Andreae COMP :10 Recursion with wrapper method /** Draw stream of bubbles from (x,y) to the top of the screen the bubbles should get larger as they go up. */ public void drawBubbles(double x, double y){ this.drawBubblesRec(x, y, 10); } /** Recursive method */ public void drawBubblesRec(double x, double y, double size){ if ( y>0 ) { this.drawBubble(x-size/2, y-size/2, size); this.drawBubblesRec(x, y-size-6, size+2); } } Do First Arguments for rest Initial size Condition Do Rest

© Peter Andreae COMP :11 Tail recursion vs nested recursion. Tail recursion: recursive call is the last step in the method. easier to understand because don’t have to “go back” after call. Nested recursion: recursive call is in the middle. have to go back to previous call to finish it off. Example: Print an “onion” : ( ( ( ( ( ( ( ) ) ) ) ) ) ) public void onion (int layers){ UI.print( “ (“ ); if (layers > 1) this.onion(layers-1); UI.print( “ )“ ); } open close do the inside

© Peter Andreae COMP :12 Nested Recursion at work onion(4) ⇒ public void onion (int layers){ UI.print( “(“ ); if (layers > 1) this.onion(layers-1); UI.print( “)“ ); public void onion (int layers){ UI.print( “ ( “ ); if (layers > 1) this.onion(layers-1); UI.print( “ ) “ ); } 4. ✔ ✔ ✔ (((()))) public void onion (int layers){ UI.print( “ ( “ ); if (layers > 1) this.onion(layers-1); UI.print( “ ) “ ); } 3. ✔ ✔ ✔ public void onion (int layers){ UI.print( “ ( “ ); if (layers > 1) this.onion(layers-1); UI.print( “ ) “ ); } 2. ✔ ✔ ✔ public void onion (int layers){ UI.print( “ ( “ ); if (layers > 1) this.onion(layers-1); UI.print( “ ) “ ); } 1. ✔ ✔ ✔

© Peter Andreae COMP :13 Nested recursion What will nested(5) print out? public void nested (int num){ if (num == 1) UI.print(“ 10 ”); else { UI.print( “(” + num + “+” ); this.nested(num-1); UI.print( “) *” + num); } (5 + (4 + (3 + ( ) * 2) * 3 ) * 4) * 5

© Peter Andreae COMP :14 Multiple Recursion Draw a recursive arch-wall: Consists of an arch with two half size arch-walls on top of it.

© Peter Andreae COMP :15 Multiple Recursion: ArchWall to draw an ArchWall of given base size (wd,ht): draw a base arch of size (wd,ht) if wd is not too small draw a half size archwall on the left draw a half size archwall on the right public void archWall (int left, int base, int wd, int ht){ this.drawArch(left, base, wd, ht); if ( wd > 20 ) { int w = wd/2; // width of next smaller arch int h = ht/2; // height of next smaller arch int mid = left+w; // height of next smaller arch int top = base-ht; // height of next smaller arch this.archWall(left, top, w, h); // left half this.archWall(mid, top, w, h); // right half }

© Peter Andreae COMP :16 Tracing the execution: archWall(10, 300, 80, 60) drawArch aw(10, 240, 40, 30) aw(50,240,40,30) drawArch aw(10,210,20,15) aw(30,210,20,15) drawArch aw(50,210,20,15) aw(70,210,20,15) drawArch

© Peter Andreae COMP :17 Multiple Recursion “Pouring” Paint in a painting program: colour this pixel spread to each of the neighbour pixels colour the pixel spread to its neighbours colour the pixel spread to its neighbours …

© Peter Andreae COMP :18 Spreading Paint private int rows = 25; private int cols = 35; private Color[ ][ ] grid = new Color[40][50]; // the grid of colours, /** Spread new colour to all adjacent cells with oldColour */ public void spread(int row, int col, Color oldColour, Color newColour){ if (row =this.rows || col =this.cols) { return; } if ( ! this.grid[row][col].equals(oldColour) ) { return; } this.setPixel(row, col, newColour); spread(row-1,col, oldColour, newColor); spread(row+1,col, oldColour, newColor); spread(row,col-1, oldColour, newColor); spread(row,col+1, oldColour, newColor); }

© Peter Andreae COMP :19 Recursion that returns a value. What if the method returns a value? ⇒ get value from recursive call, then do something with it typically, perform computation on value, then return answer. Compound interest value at end of n th year = value at end of previous year * (1 + interest). value(deposit, year) = deposit [if year is 0] = value(deposit, year-1) * (1+rate)

© Peter Andreae COMP :20 Recursion returning a value /** Compute compound interest of a deposit */ public double compound(double deposit, double rate, int years){ if (years == 0) return deposit; else return ( this.compound(deposit, rate, years-1) * (1 + rate) ); } alternative : public double compound(double deposit, double rate, int years){ if (years == 0) return deposit; else { double prev = this.compound(deposit, rate, years-1); return prev * (1 + rate); } }

© Peter Andreae COMP :21 Recursion with return: execution public double value(double deposit, double rate, int year){ if (year == 0) return deposit; else { double prev = this.value(deposit, rate, year-1);← step 1 return prev * (1 + rate); ← step 2 } } value(1000, 0.1, 4) value(1000, 0.1, 3) * 1.1 value(1000, 0.1, 2) * 1.1 value(1000, 0.1, 1) * 1.1 value(1000, 0.1, 0) *