Recursion II CSE 120 Spring 2017

Slides:



Advertisements
Similar presentations
CSC 205 Programming II Lecture 10 Towers of Hanoi.
Advertisements

Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
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.
1 Section 6.1 Recurrence Relations. 2 Recursive definition of a sequence Specify one or more initial terms Specify rule for obtaining subsequent terms.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
© 2004 Pearson Addison-Wesley. All rights reserved October 27, 2006 Recursion (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL 2006.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Data Structures Recursion Phil Tayco Slide version 1.0 Mar. 8, 2015.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
11 Project 2 Towers of Hanoi. 22 Towers of Hanoi is a well known puzzle that can be very difficult to solve manually but can be programmed very easily.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Examples of Recursion Instructor: Mainak Chaudhuri
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Recursively Defined Sequences Lecture 40 Section 8.1 Wed, Apr 11, 2007.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Review of Recursion What is a Recursive Method?
CS212: Data Structures and Algorithms
Recursion.
Expressions & Control Flow CSE 120 Spring 2017
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
COMP 51 Week Fourteen Recursion.
User-Written Functions
Basic Input and Output CSE 120 Spring 2017
Topic 6 Recursion.
Chapter 15 Recursion.
CprE 185: Intro to Problem Solving (using C)
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Chapter 15 Recursion.
Recursion I CSE 120 Spring 2017 Instructor: Teaching Assistants:
Developing an App CSE 120 Spring 2017
Functions in Processing CSE 120 Spring 2017
Lightbot and Functions CSE 120 Winter 2017
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 8: Recursion Java Software Solutions
Functions in Processing CSE 120 Winter 2018
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Basic Input and Output CSE 120 Winter 2018
Expressions & Control Flow CSE 120 Winter 2018
Algorithm design and Analysis
Recursion (part 2) October 26, 2007 ComS 207: Programming I (in Java)
Chapter 14: Recursion Starting Out with C++ Early Objects
Variables & Datatypes CSE 120 Spring 2017
Chapter 8: Recursion Java Software Solutions
Recursion Chapter 18.
Review of Recursion What is a Recursive Method?
Chapter 11 Recursion.
Chapter 8: Recursion Java Software Solutions
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Chapter 18 Recursion.
Recursion Taken from notes by Dr. Neil Moore
Variables & Datatypes CSE 120 Winter 2019
CSC 143 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Recursion (part 2) March 22, 2006 ComS 207: Programming I (in Java)
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Java Software Solutions Foundations of Program Design Sixth Edition
Recursion Chapter 12.
Review of Recursion What is a Recursive Method?
Presentation transcript:

Recursion II CSE 120 Spring 2017 Instructor: Teaching Assistants: Justin Hsia Anupam Gupta, Braydon Hall, Eugene Oh, Savanna Yee Braille Smartwatch Lets Users Feel Time, Texts And GPS Directions Facebook, texting and GPS are commonplace tech that most of us use. But these apps… can be incredibly alienating for the visually impaired and blind. The Dot smartwatch, which one could connect to a smartphone via Bluetooth, has a touch display where rising and falling dots spell out words in Braille. Other smartwatches… [utilize] sound to read information on the screen through a speaker, but this method often robs disabled users of privacy. http://www.huffingtonpost.com/entry/ braille-smartwatch-feel-messages-screen_us_58b489d1e4b060480e0aeceb

Administrivia Assignments: Mid-Quarter Survey due tonight (5/3) Recursive Tree due Thursday (5/4) Color Checker due Saturday (5/6) Living Computers Museum Report (5/14) Guest lecture on Friday: Proofs and Computation Reading Check (5/4): mathematics Midterm re-grade requests due tonight (5/3) Adjusted scores will be uploaded to Canvas after regrade requests are handled

Recursion Review A recursive function calls itself to solve its problem Base Case: What happens for special/simple inputs Need base case(s) to prevent infinite recursion Recursive Case: Function calls itself one or more times on “smaller” problems How to make the problem smaller varies ← this is the tricky part!

Outline Example: Tower of Hanoi Variable Scope Revisited Example: Fibonacci Example: Snowflake Fractal

Tower of Hanoi Mathematical puzzle/game Rules: Goal is to move entire stack from one peg to any other peg Rules: There are only 3 available pegs Can only move one disk at a time A disk cannot sit on top of a smaller one

Solving the Tower of Hanoi The animation was probably daunting, but the recursive solution is surprisingly clean Can still be mind-blowingly confusing to understand For illustrative purposes – you’re not responsible for knowing this Goal: Move the tower of height 5 from peg 1 to peg 3 Let’s assume our solution looks something of the form: moveTower(int height, int startPeg, int endPeg) 1 2 3

Solving the Tower of Hanoi To reconstruct the tower on peg 3, we first need to get the largest disk (red) onto peg 3 Can’t do this while the other disks are on top Solution: First move the 4 disks on top to peg 2 1 2 3

Solving the Tower of Hanoi To reconstruct the tower on peg 3, we first need to get the largest disk (red) onto peg 3 Can’t do this while the other disks are on top Solution: First move the 4 disks on top to peg 2 moveTower(4,peg1,peg2); ← just assume it works! 1 2 3

Solving the Tower of Hanoi Now we can move the red disk to peg 3 1 2 3

Solving the Tower of Hanoi Now we can move the red disk to peg 3 moveTower(1,peg1,peg3); Next Goal: Move the tower of height 4 from peg 2 to peg 3 Solution: First move the 3 disks on top to peg 1, then move the orange disk to peg 3 1 2 3

Solving the Tower of Hanoi Generalized recursive solution to move tower of height H from source peg to destination peg: Move tower of height H-1 from source peg to extra peg Move the remaining bottom disk from source peg to destination peg Move tower of height H-1 from extra peg to destination peg 1 2 3 “Source” “Extra” “Destination”

Solving the Tower of Hanoi Generalized recursive solution to move tower of height H from source peg to destination peg: moveTower(H-1,peg1,peg2); moveTower(1,peg1,peg3); moveTower(H-1,peg2,peg3); 1 2 3 “Source” “Extra” “Destination”

Solving the Tower of Hanoi What’s the base case? Don’t recurse (but still move disk) when H==1 1 2 3 “Source” “Extra” “Destination”

Outline Example: Tower of Hanoi Variable Scope Revisited Example: Fibonacci Example: Snowflake Fractal

Variable Scope Revisited Internal variables (i.e. parameters) only exist within the function they are declared The variables “cease to exist” when the function returns Each individual call of a recursive function contains a separate set of parameters, even though they have the same variable names Parameters have initial values set by the passed arguments

Variable Scope Revisited Local variables take precedent over variables of the same name Detail Removal: internal variable names are independent of external variable names, even if the same names are used We can think of every function call as creating a new function environment, which later disappears once the function returns Global variables exist outside of these environments and are accessible to all of them

‘Inception’ Analogy (2010 film) Each dream is a function call, each “kick” is a function return e.g. the ‘reality’ function calls the ‘Robert Fischer dream’ function Characters are the parameters – they may have the same names, but are different (clothes?) in every layer http://images.fastcompany.com/upload/INCEPTION%20infographic%20v3.5.2_dwang.jpg

Add Example Recursive add(): Environment diagram if we call add(3,2): int add(int x, int y) { if(y==0) { return x; } else { return add(x+1,y-1); } 4 return 5 x: 3 y: 2 1 3 return 5 x: 4 y: 1 2 x: 5 y: 0

Peer Instruction Question In the shown code, what will be printed after "3: "? Vote at http://PollEv.com/justinh 1 4 5 int x = 0; void setup() { x = 1; } void draw() { println("1: " + x); foo(4); println("3: " + x); noLoop(); void foo(int x) { x = x + 1; println("2: " + x);

Outline Example: Tower of Hanoi Variable Scope Revisited Example: Fibonacci Example: Snowflake Fractal

Fibonacci The Fibonacci Sequence is as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, … The first two numbers are 0 and 1 All following numbers are the sum of the previous two numbers https://en.wikipedia.org/wiki/Fibonacci_number Appeared as syllable counting in Indian mathematics, then more famously in a math puzzle regarding rabbit breeding:

Fibonacci The Fibonacci Sequence is as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, … fib(0) = 0, fib(1) = 1 Otherwise, fib(n) = fib(n-1) + fib(n-2)

Fibonacci Call Structure Call structure of add() looked like a call list It contained one recursive call: add(x+1,y-1) Fibonacci makes how many recursive calls? fib() looks like a call tree – each recursive case makes two calls to fib()

Outline Example: Tower of Hanoi Variable Scope Revisited Example: Fibonacci Example: Snowflake Fractal The following exercise is from the Beauty and Joy of Computing (BJC) curriculum: http://bjc.berkeley.edu/bjc-r/cur/programming/recur/fractals/snowflake.html

Koch Snowflake A mathematical curve that is one of the earliest fractal curves to have been described https://en.wikipedia.org/wiki/Koch_snowflake 3 arranged copies of the same fractal

Code: Triangle Copies of fractal arranged in a triangle: void draw() { noLoop(); }

Code: Triangle Copies of fractal arranged in a triangle: void draw() { translate(250,100); // start at top point rotate(radians(60)); for(int i=0; i<3; i=i+1) { line(0,0,len,0); // replace with fractal translate(len,0); rotate(radians(120)); } noLoop();

Drawing the Fractal Break each segment into 4 segments of equal length First call: Second call: Third call: Fourth call:

Code: Fractal First call: void snowflake_fractal(float len) { line(0,0,len/3,0); translate(len/3,0); rotate(radians(-60)); rotate(radians(120)); }

Code: Make It Recursive Recursive case Instead of drawing a line, draw the fractal! Each smaller segment is 1/3 the length of the larger segment Replace line() and translate() command pairs with calls to snowflake_fractal() Base case Introduce level variable Arbitrarily tells us how deep to recurse When level==0, just draw line instead of fractal

The Result Can draw snowflake fractal of arbitrary depth! level=1