Recursion (Continued)

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

MATH 224 – Discrete Mathematics
DISCUSSION OF SOME QUESTIONS ON PRELIM 2 Lecture 23 CS2110 – Spring 2015.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
2.3 More on Solving Linear Equations
Linear Systems The definition of a linear equation given in Chapter 1 can be extended to more variables; any equation of the form for real numbers.
RECURSION Lecture 7 CS2110 – Spring Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Complex objects How might you design a class called NestedRects of graphical objects that look like this? Requirements for the constructor: –Like many.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
RECURSION Lecture 7 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
Tonga Institute of Higher Education Design and Analysis of Algorithms IT 254 Lecture 8: Complexity Theory.
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
Week 6 - Wednesday.  What did we talk about last time?  Exam 1 post-mortem  Recursive running time.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Chapter 2 Section 3 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
INDUCTION Lecture 23 CS2110 – Spring 2015 A scientist gave a lecture on astronomy. He described how the earth orbits the sun, which, in turn, orbits the.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
RECURSION, CONTINUED Lecture 8 CS2110 – Fall 2015.
1 CS September 2008 Discussion of Methods: Executing method calls.If-statements. The return statement in a function. Local variables. For this and.
INDUCTION Lecture 21 CS2110 – Spring 2014 A well-known scientist (Bertrand Russell?) once gave a public lecture on astronomy. He described how the earth.
1 CS1110 Lecture 16, 26 Oct 2010 While-loops Reading for next time: Ch (arrays) Prelim 2: Tu Nov 9 th, 7:30-9pm. Last name A-Lewis: Olin 155 Last.
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2014.
1 Recursion and induction We teach these early, instead of new object- oriented ideas, so that those who are new to Java can have a chance to catch up.
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2015.
Sorting and Runtime Complexity CS255. Sorting Different ways to sort: –Bubble –Exchange –Insertion –Merge –Quick –more…
RECURSION (CONTINUED) Lecture 9 CS2110 – Spring 2016.
Recursion Powerful Tool
Programming with Recursion
Recursion (Continued)
Recursion (Continued)
Searching.
Correctness issues and Loop invariants
CS/ENGRD 2110 Fall 2017 Lecture 3: Fields, getters and setters, constructors, testing
More Simple Recursive Problems
Recursion (Continued)
Chapter 2 Section 3.
Recursion (Continued)
Programming with Recursion
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursion 12-Nov-18.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Last Class We Covered Data representation Binary numbers ASCII values
Recursion 2-Dec-18.
Recursion 2-Dec-18.
Sit next to someone. Today, we do some work in pairs.
Last Class We Covered Dictionaries Hashing Dictionaries vs Lists
CS1110 Lec Oct 2010 More on Recursion
Recursion 29-Dec-18.
Sit next to someone. Today, we do some work in pairs.
Recap Week 2 and 3.
Announcements Prelim 1 on Tuesday! A4 will be posted today
Algorithms: the big picture
Recursion (Continued)
Ch. 2: Getting Started.
Chapter 2 Section 3.
Searching.
CSC 143 Binary Search Trees.
Asymptotic complexity
Recursion 23-Apr-19.
Chapter 18 Recursion.
2 Equations, Inequalities, and Applications.
Copyright © 2008 Pearson Education, Inc
Searching and Sorting Hint at Asymptotic Complexity
CS100A Lecture 25 1 December 1998 Chance to replace grade on Prelim 3, Question 2. Everyone is expected to be in lecture on Thursday, 3 December.
Searching and Sorting Hint at Asymptotic Complexity
Presentation transcript:

Recursion (Continued) Lecture 9 CS2110 – Spring 2018

Prelim one week from today: 27 September. Visit Exams page of course website, check what time your prelim is, complete assignment P1Conflict ONLY if necessary. DUE TONIGHT!! Review session Sunday, 23 September, 1-3PM. A3 is due after the prelim, but start on it NOW. If appropriate, please check JavaHyperText before posting a question on the Piazza. Get your answer instantaneously rather than have to wait for a Piazza answer. Examples: “default”, “access”, “modifier”, “private” are well-explained JavaHyperText

How do we write the second PhD constructor? /** Constructor: name n, year y, month m,      * first advisor adv1, no second advisor.      * Pre: n has >=2 chars, m in 1..12, adv1 is not null. */ public PhD(String n, int y, int m, PhD adv1) { } /** Add p as first advisor of this PhD.      * Prec: first advisor is unknown, p is not null. */     public void addAdvisor1(PhD p) /** Constructor: instance with name n, year y, and month m.       * Advisors are unknown, has no advisees.      * Precondition: n has at least 2 chars, m is in 1..12. */     public PhD(String n, int y, int m)

What’s wrong with this return statement? public boolean isSiblingOf(PhD p) { assert p != null; return ((this!=p) && ((this.advisor1() != null && (this.advisor1()==p.advisor1() || this.advisor1() == p.advisor2()) || (this.advisor2() != null && (this.advisor2() == p.advisor1())) || this.advisor1()==p.advisor2()))); } 2018fa_a1Student Present the expression so that its structure is clear Avoid unnecessary use of “this.” Void unnecessary parentheses Spaces around operators In this class, use fields, rather than function calls Main reason to do this. It helps YOU make fewer mistakes

// invariant: p = product of c[0..k-1] what’s the product when k == 0? Why is the product of an empty bag of values 1? Suppose bag b contains 2, 2, 5 and p is its product: 20. Suppose we want to add 4 to the bag and keep p the product. We do: put 4 into the bag; p= 4 * p; Suppose bag b is empty and p is its product: what value? Suppose we want to add 4 to the bag and keep p the product. We do the same thing: put 4 into the bag; p= 4 * p; For this to work, the product of the empty bag has to be 1, since 4 = 1 * 4

gcd: greatest common divisor of the elements of the bag 0 is the identity of + because 0 + x = x 1 is the identity of * because 1 * x = x false is the identity of || because false || b = b true is the identity of && because true && b = b 1 is the identity of gcd because gcd({1, x}) = x For any such operator o, that has an identity, o of the empty bag is the identity of o. Sum of the empty bag = 0 Product of the empty bag = 1 OR (||) of the empty bag = false. gcd of the empty bag = 1 gcd: greatest common divisor of the elements of the bag

Recap: Understanding Recursive Methods Have a precise specification Check that the method works in the base case(s). 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. 4. (No infinite recursion) Make sure that the args of recursive calls are in some sense smaller than the pars of the method. http://codingbat.com/java/Recursion-1

Problems with recursive structure Code will be available on the course webpage. exp - exponentiation, the slow way and the fast way perms – list all permutations of a string tile-a-kitchen – place L-shaped tiles on a kitchen floor drawSierpinski – drawing the Sierpinski Triangle

Computing bn for n >= 0 Power computation: b0 = 1 If n != 0, bn = b * bn-1 If n != 0 and even, bn = (b*b)n/2 Judicious use of the third property gives far better algorithm Example: 38 = (3*3) * (3*3) * (3*3) * (3*3) = (3*3) 4

Computing bn for n >= 0 Power computation: b0 = 1 If n != 0, bn = b bn-1 If n != 0 and even, bn = (b*b)n/2 Suppose n = 16 Next recursive call: 8 Next recursive call: 4 Next recursive call: 2 Next recursive call: 1 Then 0 /** = b**n. Precondition: n >= 0 */ static int power(double b, int n) { if (n == 0) return 1; if (n%2 == 0) return power(b*b, n/2); return b * power(b, n-1); } 16 = 2**4 Suppose n = 2**k Will make k + 2 calls

Computing bn for n >= 0 If n = 2**k k is called the logarithm (to base 2) of n: k = log n or k = log(n) Suppose n = 16 Next recursive call: 8 Next recursive call: 4 Next recursive call: 2 Next recursive call: 1 Then 0 /** = b**n. Precondition: n >= 0 */ static int power(double b, int n) { if (n == 0) return 1; if (n%2 == 0) return power(b*b, n/2); return b * power(b, n-1); } 16 = 2**4 Suppose n = 2**k Will make k + 2 calls

Difference between linear and log solutions? /** = b**n. Precondition: n >= 0 */ static int power(double b, int n) { if (n == 0) return 1; return b * power(b, n-1); } Number of recursive calls is n Number of recursive calls is ~ log n. /** = b**n. Precondition: n >= 0 */ static int power(double b, int n) { if (n == 0) return 1; if (n%2 == 0) return power(b*b, n/2); return b * power(b, n-1); } To show difference, we run linear version with bigger n until out of stack space. Then run log one on that n. See demo.

Table of log to the base 2 k n = 2^k log n (= k) 0 1 0 1 2 1 2 4 2 0 1 0 1 2 1 2 4 2 3 8 3 4 16 4 5 32 5 6 64 6 7 128 7 8 256 8 9 512 9 1024 10 2148 11 15 32768 15

Permutations of a String perms(abc): abc, acb, bac, bca, cab, cba abc acb bac bca cab cba Recursive definition: Each possible first letter, followed by all permutations of the remaining characters.

Tiling Elaine’s kitchen Kitchen in Gries’s house: 8 x 8. Fridge sits on one of 1x1 squares His wife, Elaine, wants kitchen tiled with el-shaped tiles –every square except where the refrigerator sits should be tiled. 8 /** tile a 23 by 23 kitchen with 1 square filled. */ public static void tile(int n) We abstract away keeping track of where the filled square is, etc.

Tiling Elaine’s kitchen /** tile a 2n by 2n kitchen with 1 square filled. */ public static void tile(int n) { } We generalize to a 2n by 2n kitchen if (n == 0) return; Base case?

Tiling Elaine’s kitchen /** tile a 2n by 2n kitchen with 1 square filled. */ public static void tile(int n) { } 2n if (n == 0) return; n > 0. What can we do to get kitchens of size 2n-1 by 2n-1

Tiling Elaine’s kitchen /** tile a 2n by 2n kitchen with 1 square filled. */ public static void tile(int n) { } if (n == 0) return; We can tile the upper-right 2n-1 by 2n-1 kitchen recursively. But we can’t tile the other three because they don’t have a filled square. What can we do? Remember, the idea is to tile the kitchen!

Tiling Elaine’s kitchen /** tile a 2n by 2n kitchen with 1 square filled. */ public static void tile(int n) { } if (n == 0) return; Place one tile so that each kitchen has one square filled; Tile upper left kitchen recursively; Tile upper right kitchen recursively; Tile lower left kitchen recursively; Tile lower right kitchen recursively;

Sierpinski triangles S triangle of depth 0 S triangle of depth 1: 3 S triangles of depth 0 drawn at the 3 vertices of the triangle S triangle of depth 2: 3 S triangles of depth 1 drawn at the 3 vertices of the triangle

Sierpinski triangles S triangle of depth 0: the triangle S triangle of depth d at points p1, p2, p3: 3 S triangles of depth d-1 drawn at at p1, p2, p3 p3 Sierpinski triangles of depth d-1 p2 p1

Sierpinski triangles x y s 3 /2 s/2 s s/4

Conclusion Recursion is a convenient and powerful way to define functions Problems that seem insurmountable can often be solved in a “divide-and-conquer” fashion: Reduce a big problem to smaller problems of the same kind, solve the smaller problems Recombine the solutions to smaller problems to form solution for big problem http://codingbat.com/java/Recursion-1