CompSci 100 8.1 Review of Recursion with Big-Oh  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.

Slides:



Advertisements
Similar presentations
More Recursion: Permutations and Towers of Hanoi COP 3502.
Advertisements

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.
Recursion. Recursive Definitions A recursive definition is one which uses the word being defined in the definition Not always useful:  for example, in.
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.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
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.
When confronted with a new problem there are two questions you should ask: 1. Is this problem like, or a special case of, a problem that I already know.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
1 Storage Classes, Scope, and Recursion Lecture 6.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
CompSci 100E 10.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
CPS 100, Spring From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
CompSci 100 Prog Design and Analysis II Sept 16, 2010 Prof. Rodger CompSci 100, Fall
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 8 Recursion Modified.
CompSci 100E 12.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
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.
CompSci 100e 6.1 Hashing: Log ( ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Compsci 100, Fall From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
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.
Recursion Review: A recursive function calls itself, but with a smaller problem – at least one of the parameters must decrease. The function uses the results.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems.
CompSci Analyzing Algorithms  Consider three solutions to SortByFreqs, also code used in Anagram assignment  Sort, then scan looking for changes.
CompSci 100E 15.1 What is a Binary Search?  Magic!  Has been used a the basis for “magical” tricks  Find telephone number ( without computer ) in seconds.
CPS Today’s topics Programming Recursion Copyrights, patents, and digital media Reading Great Ideas, p Brookshear, Section Online.
CompSci 100e 7.1 Hashing: Log ( ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Recursion Fundamentals of Recursion l Base case (aka exit case)  Simple case that can be solved with no further computation  Does not make a recursive.
CPS Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved simply.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit ä Allows many complex problems.
Recursion. What is Recursion? Method of solving problems Alternative to iteration All recursive solutions can be implemented iteratively Characteristic...
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
A Computer Science Tapestry 1 Announcements l Please complete the Course Evaluations l Final exam on December 24, 2015, Thursday ä at 16:00 (more info.
CPS Today’s topics Programming Recursion Invariants Reading Great Ideas, p Brookshear, Section Upcoming Copyrights, patents, and.
Welcome to Recursion! Say what?!? Recursion is… the process of solving large problems by simplifying them into smaller ones. similar to processing using.
Recursion Chapter 2 Objectives Upon completion you will be able to:
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion: The Mirrors
Plan for the Week Review for Midterm Source code provided
RECURSION.
Solving Problems Recursively
Decrease-and-Conquer Approach
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursive Definitions
Announcements Final Exam on August 19th Saturday at 16:00.
Announcements Final Exam on December 25th Monday at 16:00.
Announcements HW3 grades will be announced this week
Solving Problems Recursively
Solving Problems Recursively
Presentation transcript:

CompSci Review of Recursion with Big-Oh  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 (and sometimes more efficient!!)  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

CompSci Keys to Recursion  Recursive functions have two key attributes  There is a base case, sometimes called the halting or exit case, which does not make a recursive call  All other cases make a recursive call, with some parameter or other measure that decreases or moves towards the base case o Ensure that sequence of calls eventually reaches the base case o “Measure” can be tricky, but usually it’s straightforward  Most of you have seen the following before in CompSci 6  This time, go faster  Concentrate on Recurrence Relations and Big-Oh  Should now be able to make a more sophisticated evaluation

CompSci 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() { // some I/O details omitted String word; word = console.readLine(); if (word.length() > 0) { // get something? printReversed(); // print the rest reversed System.out.println(word); // then print the word } // somewhere in 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  Recurrence Relations? Big-Oh? Space?

CompSci 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? x^n */ double power(double x, int n){ if (n == 0){ return 1.0; } return x * power(x, n-1); }  Recurrence Relations? Big-Oh?

CompSci Faster exponentiation  How many recursive calls are made to computer ?  How many multiplies on each call? Is this better? x^n */ double power(double x, int n){ if (n == 0) { return 1.0; } double semi = power(x, n/2); if (n % 2 == 0) {// is n even? return semi*semi; } return x * semi * semi; {// n must be odd }  Recurrence Relations? Big-Oh?

CompSci Classic examples of recursion  For some reason, computer science uses these examples:  Factorial: we can use a loop or recursion. Is this an issue?  Fibonacci numbers: 1, 1, 2, 3, 5, 8, 13, 21, … o F(n) = F(n-1) + F(n-2), why isn’t this enough? What’s needed? o 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 o N disks on one of three pegs, transfer all disks to another peg, never put a disk on a smaller one, only on larger o Every solution takes “forever” when N, number of disks, is large

CompSci Fibonacci: Don’t do this recursively n >= 0 n-th Fibonacci * number */ long recFib(int n) { if (0 == n || 1 == n) { return 1; } else { return recFib(n-1) + recFib(n-2); }  How many clones/calls to compute F(5)?  Recurrence Relations? Big-Oh? How many calls of F(1)? How many total calls? consider caching code

CompSci Towers of Hanoi  Move n disks from one peg to another with restrictive rules /** disks moved from peg 'from‘ * to peg 'to' using peg 'aux' numDisks on peg # from from source peg # to target peg # aux peg # for parking */ void move(int from, int to, int aux, int numDisks) { if (numDisks == 1) { System.out.println("move " + from + " to " + to ); } else { move(from,aux,to, numDisks - 1); move(from,to,aux, 1); move(aux,to,from, numDisks - 1); }  Recurrence Relations? Big-Oh? Peg#1 #2 #3

CompSci 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: instance variables  Instance variable: maintains value over all function calls  Local variables created each time function called

CompSci Fixing recursive Fibonacci n >= 0 and n <= 30 the n-th Fibonacci number */ long recFib(int n) { long[] mem = new long[31]; Arrays.fill(mem, 0); return recF (n, mem); } long recF(int n, long[] mem){ if (0 == n || 1 == n) return 1; else if (mem[n] != 0) return mem[n]; else { mem[n] = recF(n-1, mem) + recF(n-2, mem); return mem[n]; }  What does mem do? Why initialize to all zeros?  Recurrence too complicated for our simple methods

CompSci Recursive Max a contains a.length elements, 0 < a.length first < a.length is index to start maximal element of a[first..length-1] */ double recMax(double[] a, int first) { if (first == a.length-1){ // last element, done return a[first]; } double maxAfter = recMax(a, first+1); if (maxAfter < a[first]) return a[first]; else return maxAfter; }  What is base case (conceptually)?  We can use recMax to implement max as follows return recMax(a,0);  Recurrence Relations? Big-Oh?

CompSci Recognizing recursion: /** a is changed */ void change(int[] a, int first, int last) { 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.length-1);  What is base case? (no recursive calls)  Recurrence Relations? Big-Oh?