Lecture 8 CS2110 Fall 2018 RECURSION

Similar documents
Lecture 8 CS2110 Spring 2018 RECURSION

Lecture 8 CS2110 Spring 2017 RECURSION

21/02/2018. six items RECURSION. Recursion Real Life Examples. To Understand Recursion. Recursion Real Life Examples

Recursion Real Life Examples. To Understand Recursion. Recursion Real Life Examples 9/13/17. Five things RECURSION

Lecture 8 CS2110 Fall 2016 RECURSION

It s turtles all the way down RECURSION

Gries slides on A2 function evaluate and evaluate itself are on pinned Piazza note Supplementary Material 1 is the identity of gcd because

Assignment 4. Stop by the LaIR! Stop by office hours! your section leader!

RECURSION (CONTINUED)

Review from Last Time

Lecture 7 CS2110 Fall 2014 RECURSION

9/16/14. Overview references to sections in text RECURSION. What does generic mean? A little about generics used in A3

Assignment 2. Number of Students Time Spent (hours) Piech, CS106A, Stanford University

Lecture 6: Recursion RECURSION

Lecture 6 CS2110 Spring 2013 RECURSION

RECURSION. Many Slides from Ken Birman, Cornell University

Strings. Piech, CS106A, Stanford University

Recursive definition: A definition that is defined in terms of itself. Recursive method: a method that calls itself (directly or indirectly).

RECURSION (CONTINUED)

Utility Functions. 3.1 Introduction

Recursion. Recursion [Bono] 1

If you are going to form a group for A2, please do it before tomorrow (Friday) noon GRAMMARS & PARSING. Lecture 8 CS2110 Spring 2014

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

CS 3410 Ch 7 Recursion

Table of Contents. Phonics

GRAMMARS & PARSING. Lecture 7 CS2110 Fall 2013

RECURSION (CONTINUED)

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

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims

CS/ENGRD 2110 SPRING 2018

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

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!

Grammars & Parsing. Lecture 12 CS 2112 Fall 2018

CSE 143 SAMPLE MIDTERM

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

CMPSCI 250: Introduction to Computation. Lecture #14: Induction and Recursion (Still More Induction) David Mix Barrington 14 March 2013

Lecture 13. Call Stacks & Debugging

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

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

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

CS Introduction to Data Structures Week 4, 2017

CS : Data Structures

ASTS, GRAMMARS, PARSING, TREE TRAVERSALS. Lecture 14 CS2110 Fall 2018

syntax tree - * * * * * *

[2:3] Linked Lists, Stacks, Queues

Pace University. Fundamental Concepts of CS121 1

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Recursion. Fundamentals of Computer Science

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

Recursive Definitions

Data Structures. BSc in Computer Science University of New York, Tirana. Assoc. Prof. Marenglen Biba 1-1

Announcements. Application of Recursion. Motivation. A Grammar. A Recursive Grammar. Grammars and Parsing

CS 251 Intermediate Programming Methods and Classes

Review sheet for Final Exam (List of objectives for this course)

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

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

CS1150 Principles of Computer Science Methods

CS1 Recitation. Week 2

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

CS1 Lecture 15 Feb. 19, 2018

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Programming & Data Structure

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

CS 251 Intermediate Programming Methods and More

Reduction & Recursion Overview

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Answer Key: Let s Go Phonics Book 1

ADTS, GRAMMARS, PARSING, TREE TRAVERSALS

Unit #3: Recursion, Induction, and Loop Invariants

Data Structures And Algorithms

Total Score /15 /20 /30 /10 /5 /20 Grader

CS 211: Recursion. Chris Kauffman. Week 13-1

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

CS 61B Discussion 5: Inheritance II Fall 2014

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

Unit #2: Recursion, Induction, and Loop Invariants

CS 137 Part 9. Fibonacci, More on Tail Recursion, Map and Filter. November 22nd, 2017

STUDENT LESSON A9 Recursion

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

CSE 143. Computer Programming II

CS1150 Principles of Computer Science Methods

Australian researchers develop typeface they say can boost memory, that could help students cramming for exams.

Dealing with Bugs. Kenneth M. Anderson University of Colorado, Boulder CSCI 5828 Lecture 27 04/21/2009

Data Abstraction and Specification of ADTs

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

Run-Time Data Structures

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

Function Calling Conventions 2 CS 64: Computer Organization and Design Logic Lecture #10

Chapter 17 Recursion

CSC 1052 Algorithms & Data Structures II: Recursion

Transcription:

Lecture 8 CS2110 Fall 2018 RECURSION

five items 2 Note: We ve covered almost everything in Java! Just a few more things, which will be covered from time to time. Remember to look at the exams page of course website and, if necessary, complete P1Conflict on CMS or email Jenna by THURSDAY NIGHT A1 grades are available. PLEASE READ YOUR FEEDBACK! Mean: 93.9 Median: 97 Recursion: Look at Java Hypertext entry recursion. Note: Remember to do the tutorial for this week s recitation. It is really important that you master this material.

About A3. linked list data structure 3 This is a linked list containing the list of integers (6, 7, 3). header, containing size of list and pointer to first node Each node (N@1, N@8, N@2) contains a value of the list and a pointer to next node (null if none) Why use linked list? Can insert a value at beginning of list with just a few instructions ---constant time 3

A3 introduces generics 4 Generic programming: a style of computer programming in which algorithms are written in terms of types to be specified later, which are then instantiated when needed for specific types. 4

A3 introduces generics 5 /** An instance maintains a set of some max size. */ public class TimeSet <E> { // E is a type parameter private Entry[] s; // The set elements are in s[0..n-1] private int n; // size of set. new TimeSet(10) This set can contain any values, e.g. {6, xy, 5.2, a new TimeSet<String>(10) This set can contain only Strings, e.g. { xy, a 5

A3 introduces generics 6 /** An instance maintains a set of some max size. */ public class TimeSet <E> { // E is a type parameter private Entry[] s; // The set elements are in s[0..n-1] private int n; // size of set. 6

A3 introduces inner classes 7 /** An instance represents a linked list */ public class TimeSet <E> { // E is a type parameter private Node first; // first node of list (null if size 0) private int size; // Number of values. /** An instance holds an E element. */ private class Entry { private E val; // the element of type E private long t; // the time at which entry was created. Note how type parameter E is used new TimeSet<String> // E will be String 7

To Understand Recursion 8

Recursion Real Life Examples 9 <noun phrase> is <noun>, or <adjective> <noun phrase>, or <adverb> <noun phrase> Example: terrible horrible no-good very bad day

Recursion Real Life Examples 10 <noun phrase> is <noun>, or ancestor(p) is parent(p), or 0! = 1 n! = n * (n-1)! <adjective> <noun phrase>, or <adverb> <noun phrase> parent(ancestor(p)) great great great great great great great great great great great great great grandmother. 1, 1, 2, 6, 24, 120, 720, 5050, 40320, 362880, 3628800, 39916800, 479001600

Sum the digits in a non-negative integer 11 /** = sum of digits in n. * Precondition: n >= 0 */ public static int sum(int n) { if (n < 10) return n; sum calls itself! // { n has at least two digits // return first digit + sum of rest return n%10 + sum(n/10); sum(7) = 7 sum(8703) = 3 + sum(870) = 3 + 8 + sum(70) = 3 + 8 + 7 + sum(0)

Two different questions, two different answers 12 1. How is it executed? (or, why does this even work?) 2. How do we understand recursive methods? (or, how do we write/develop recursive methods?)

Stacks and Queues 13 stack grows top element 2nd element... bottom element Stack: list with (at least) two basic ops: * Push an element onto its top * Pop (remove) top element Last-In-First-Out (LIFO) Like a stack of trays in a cafeteria first second last Americans wait in a line. The Brits wait in a queue! Queue: list with (at least) two basic ops: * Append an element * Remove first element First-In-First-Out (FIFO)

Stack Frame 14 A frame contains information about a method call: At runtime Java maintains a a frame stack that contains frames for all method calls that are being executed but have not completed. local variables parameters Method call: push a frame for call on stack. Assign argument values to parameters. Execute method body. Use the frame for the call to reference local variables and parameters. End of method call: pop its frame from the stack; if it is a function leave the return value on top of stack.

16 Memorize method call execution! A frame for a call contains parameters, local variables, and other information needed to properly execute a method call. To execute a method call: 1. push a frame for the call on the stack, 2. assign argument values to parameters, 3. execute method body, 4. pop frame for call from stack, and (for a function) push returned value on stack When executing method body look in frame for call for parameters and local variables.

Frames for methods sum main method in the system 17 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); frame: n public static void main( String[] args) { int r= sum(824); System.out.println(r); Frame for method in the system that calls method main frame: frame: r args?

Example: Sum the digits in a non-negative integer 18 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); public static void main( String[] args) { int r= sum(824); System.out.println(r); Frame for method in the system that calls method main: main is then called main system r args?

Memorize method call execution! 19 To execute a method call: 1. push a frame for the call on the stack, 2. assign argument values to parameters, 3. execute method body, 4. pop frame for call from stack, and (for a function) push returned value on stack The following slides step through execution of a recursive call to demo execution of a method call. Here, we demo using: www.pythontutor.com/visualize.html Caution: the frame shows not ALL local variables but only those whose scope has been entered and not left.

Example: Sum the digits in a non-negative integer 20 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); public static void main( String[] args) { int r= sum(824); System.out.println(r); Method main calls sum: main system n 824 r args?

Example: Sum the digits in a non-negative integer 21 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); public static void main( String[] args) { int r= sum(824); System.out.println(r); n >= 10 sum calls sum: main system n 82 n 824 r args?

Example: Sum the digits in a non-negative integer 22 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); public static void main( String[] args) { int r= sum(824); System.out.println(r); n >= 10. sum calls sum: main system n 8 n 82 n 824 r args?

Example: Sum the digits in a non-negative integer 23 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); public static void main( String[] args) { int r= sum(824); System.out.println(r); n < 10 sum stops: frame is popped and n is put on stack: main system n 8 return 8 info n 82 n 824 r args?

Example: Sum the digits in a non-negative integer 24 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); public static void main( String[] args) { int r= sum(824); System.out.println(r); Using return value 8 stack computes 2 + 8 = 10 pops frame from stack puts return value 10 on stack main 8 n 82 return 10 info n 824 r args?

Example: Sum the digits in a non-negative integer 25 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); public static void main( String[] args) { int r= sum(824); System.out.println(r); Using return value 10 stack computes 4 + 10 = 14 pops frame from stack puts return value 14 on stack main 10 n 824 return 14 info r args?

Example: Sum the digits in a non-negative integer 26 public static int sum(int n) { if (n < 10) return n; return n%10 + sum(n/10); public static void main( String[] args) { int r= sum(824); System.out.println(r); Using return value 14 main stores 14 in r and removes 14 from stack main 14 r 14 args?

27 Poll time!

Two different questions, two different answers 28 1. How is it executed? (or, why does this even work?) It s not magic! Trace the code s execution using the method call algorithm, drawing the stack frames as you go. Use only to gain understanding / assurance that recursion works. 2. How do we understand recursive methods? (or, how do we write/develop recursive methods?) This requires a totally different approach.

Back to Real Life Examples 29 Factorial function: 0! = 1 n! = n * (n-1)! for n > 0 (e.g.: 4! = 4*3*2*1=24) Exponentiation: b 0 = 1 b c = b * b c-1 for c > 0 Easy to make math definition into a Java function! public static int fact(int n) { if (n == 0) return 1; return n * fact(n-1); public static int exp(int b, int c) { if (c == 0) return 1; return b * exp(b, c-1);

How to understand what a call does 30 Make a copy of the method spec, replacing the parameters of the method by the arguments spec says that the value of a call equals the sum of the digits of n sumdigs(654) sum of digits of n sum of digits of 654 /** = sum of the digits of n. * Precondition: n >= 0 */ public static int sumdigs(int n) { if (n < 10) return n; // n has at least two digits return n%10 + sumdigs(n/10);

Understanding a recursive method 31 Step 1. Have a precise spec! Step 2. Check that the method works in the base case(s): That is, Cases where the parameter is small enough that the result can be computed simply and without recursive calls. If n < 10 then n consists of a single digit. Looking at the spec we see that that digit is the required sum. /** = sum of the digits of n. * Precondition: n >= 0 */ public static int sumdigs(int n) { if (n < 10) return n; // n has at least two digits return n%10 + sumdigs(n/10);

Understanding a recursive method 32 Step 1. Have a precise spec! Step 2. Check that the method works in the base case(s). Step 3. Look at the recursive case(s). In your mind replace each recursive call by what it does according to the method spec and verify that the correct result is then obtained. return n%10 + sum(n/10); /** = sum of the digits of n. * Precondition: n >= 0 */ public static int sumdigs(int n) { if (n < 10) return n; // n has at least two digits return n%10 + sumdigs(n/10); return n%10 + (sum of digits of n/10); // e.g. n = 843

Understanding a recursive method 33 Step 1. Have a precise spec! Step 2. Check that the method works in the base case(s). Step 3. Look at the recursive case(s). In your mind replace each recursive call by what it does acc. to the spec and verify correctness. /** = sum of the digits of n. * Precondition: n >= 0 */ public static int sumdigs(int n) { if (n < 10) return n; // n has at least two digits return n%10 + sumdigs(n/10); Step 4. (No infinite recursion) Make sure that the args of recursive calls are in some sense smaller than the pars of the method. n/10 < n, so it will get smaller until it has one digit

Understanding a recursive method 34 Step 1. Have a precise spec! Step 2. Check that the method works in the base case(s). Step 3. Look at the recursive case(s). In your mind replace each recursive call by what it does according to the spec and verify correctness. Important! Can t do step 3 without precise spec. Once you get the hang of it this is what makes recursion easy! This way of thinking is based on math induction which we don t cover in this course. Step 4. (No infinite recursion) Make sure that the args of recursive calls are in some sense smaller than the parameters of the method

Writing a recursive method 35 Step 1. Have a precise spec! Step 2. Write the base case(s): Cases in which no recursive calls are needed. Generally for small values of the parameters. Step 3. Look at all other cases. See how to define these cases in terms of smaller problems of the same kind. Then implement those definitions using recursive calls for those smaller problems of the same kind. Done suitably, point 4 (about termination) is automatically satisfied. Step 4. (No infinite recursion) Make sure that the args of recursive calls are in some sense smaller than the parameters of the method

Two different questions, two different answers 36 2. How do we understand recursive methods? (or, how do we write/develop recursive methods?) Step 1. Have a precise spec! Step 2. Check that the method works in the base case(s). Step 3. Look at the recursive case(s). In your mind replace each recursive call by what it does according to the spec and verify correctness. Step 4. (No infinite recursion) Make sure that the args of recursive calls are in some sense smaller than the parameters of the method

Examples of writing recursive functions 37 For the rest of the class we demo writing recursive functions using the approach outlined below. The java file we develop will be placed on the course webpage some time after the lecture. Step 1. Have a precise spec! Step 2. Write the base case(s). Step 3. Look at all other cases. See how to define these cases in terms of smaller problems of the same kind. Then implement those definitions using recursive calls for those smaller problems of the same kind. Step 4. Make sure recursive calls are smaller (no infinite recursion).

Check palindrome-hood 38 A String palindrome is a String that reads the same backward and forward: ispal( racecar ) à true ispal( pumpkin ) à false A String with at least two characters is a palindrome if (0) its first and last characters are equal and (1) chars between first & last form a palindrome: have to be the same e.g. AMANAPLANACANALPANAMA have to be a palindrome A recursive definition!

39 A man a plan a caret a ban a myriad a sum a lac a liar a hoop a pint a catalpa a gas an oil a bird a yell a vat a caw a pax a wag a tax a nay a ram a cap a yam a gay a tsar a wall a car a luger a ward a bin a woman a vassal a wolf a tuna a nit a pall a fret a watt a bay a daub a tan a cab a datum a gall a hat a fag a zap a say a jaw a lay a wet a gallop a tug a trot a trap a tram a torr a caper a top a tonk a toll a ball a fair a sax a minim a tenor a bass a passer a capital a rut an amen a ted a cabal a tang a sun an ass a maw a sag a jam a dam a sub a salt an axon a sail an ad a wadi a radian a room a rood a rip a tad a pariah a revel a reel a reed a pool a plug a pin a peek a parabola a dog a pat a cud a nu a fan a pal a rum a nod an eta a lag an eel a batik a mug a mot a nap a maxim a mood a leek a grub a gob a gel a drab a citadel a total a cedar a tap a gag a rat a manor a bar a gal a cola a pap a yaw a tab a raj a gab a nag a pagan a bag a jar a bat a way a papa a local a gar a baron a mat a rag a gap a tar a decal a tot a led a tic a bard a leg a bog a burg a keel a doom a mix a map an atom a gum a kit a baleen a gala a ten a don a mural a pan a faun a ducat a pagoda a lob a rap a keep a nip a gulp a loop a deer a leer a lever a hair a pad a tapir a door a moor an aid a raid a wad an alias an ox an atlas a bus a madam a jag a saw a mass an anus a gnat a lab a cadet an em a natural a tip a caress a pass a baronet a minimax a sari a fall a ballot a knot a pot a rep a carrot a mart a part a tort a gut a poll a gateway a law a jay a sap a zag a fat a hall a gamut a dab a can a tabu a day a batt a waterfall a patina a nut a flow a lass a van a mow a nib a draw a regular a call a war a stay a gam a yap a cam a ray an ax a tag a wax a paw a cat a valley a drib a lion a saga a plat a catnip a pooh a rail a calamus a dairyman a bater a canal Panama

Example: Is a string a palindrome? 40 /** = "s is a palindrome" */ public static boolean ispal(string s) { if (s.length() <= 1) return true; Substring from s[1] to s[n-1] // { s has at least 2 chars int n= s.length()-1; return s.charat(0) == s.charat(n) && ispal(s.substring(1,n));

The Fibonacci Function 41 Mathematical definition: fib(0) = 0 two base cases! fib(1) = 1 fib(n) = fib(n - 1) + fib(n - 2) n 2 Fibonacci sequence: 0 1 1 2 3 5 8 13 /** = fibonacci(n). Pre: n >= 0 */ static int fib(int n) { if (n <= 1) return n; // { 1 < n return fib(n-1) + fib(n-2); Fibonacci (Leonardo Pisano) 1170-1240? Statue in Pisa Italy Giovanni Paganucci 1863

Example: Count the e s in a string 42 /** = number of times c occurs in s */ public static int countem(char c, String s) { if (s.length() == 0) return 0; // { s has at least 1 character if (s.charat(0)!= c) return countem(c, s.substring(1)); // { first character of s is c return 1 + countem (c, s.substring(1)); countem( e, it is easy to see that this has many e s ) = 4 countem( e, Mississippi ) = 0 substring s[1..] i.e. s[1] s(s.length()-1)