Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

Similar documents
Recursion. Jordi Cortadella Department of Computer Science

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

CIS 121. Introduction to Trees

Ones Assignment Method for Solving Traveling Salesman Problem

Algorithm Design Techniques. Divide and conquer Problem

Algorithm. Counting Sort Analysis of Algorithms

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Mathematics. Programming

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Inductive Definition to Recursive Function

Python Programming: An Introduction to Computer Science

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

How do we evaluate algorithms?

Lecture 1: Introduction and Strassen s Algorithm

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Counting the Number of Minimum Roman Dominating Functions of a Graph

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Recursion. A problem solving technique where an algorithm is defined in terms of itself. A recursive method is a method that calls itself

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

CHAPTER IV: GRAPH THEORY. Section 1: Introduction to Graphs

Homework 1 Solutions MA 522 Fall 2017

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

condition w i B i S maximum u i

NTH, GEOMETRIC, AND TELESCOPING TEST

why study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.

. Written in factored form it is easy to see that the roots are 2, 2, i,

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

Chapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

CSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.

BOOLEAN MATHEMATICS: GENERAL THEORY

Examples and Applications of Binary Search

From last week. Lecture 5. Outline. Principles of programming languages

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Sorting 9/15/2009. Sorting Problem. Insertion Sort: Soundness. Insertion Sort. Insertion Sort: Running Time. Insertion Sort: Soundness

Lecture 9: Exam I Review

1. (a) Write a C program to display the texts Hello, World! on the screen. (2 points)

CS 11 C track: lecture 1

Computational Geometry

! Given the following Structure: ! We can define a pointer to a structure. ! Now studentptr points to the s1 structure.

Lecture 5: Recursion. Recursion Overview. Recursion is a powerful technique for specifying funclons, sets, and programs

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

A graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))

CMPT 125 Assignment 2 Solutions

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

CSE 417: Algorithms and Computational Complexity

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Math Section 2.2 Polynomial Functions

On Infinite Groups that are Isomorphic to its Proper Infinite Subgroup. Jaymar Talledo Balihon. Abstract

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

top() Applications of Stacks

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

5.3 Recursive definitions and structural induction

Computers and Scientific Thinking

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

An Improved Shuffled Frog-Leaping Algorithm for Knapsack Problem

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Recursive Procedures. How can you model the relationship between consecutive terms of a sequence?

Exercise 6 (Week 42) For the foreign students only.

Lower Bounds for Sorting

Informed Search. Russell and Norvig Chap. 3

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

It just came to me that I 8.2 GRAPHS AND CONVERGENCE

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 3 Classification of FFT Processor Algorithms

Reliable Transmission. Spring 2018 CS 438 Staff - University of Illinois 1

The isoperimetric problem on the hypercube

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

1.2 Binomial Coefficients and Subsets

New Results on Energy of Graphs of Small Order

Python Programming: An Introduction to Computer Science

Octahedral Graph Scaling

Exact Minimum Lower Bound Algorithm for Traveling Salesman Problem

CS280 HW1 Solution Set Spring2002. now, we need to get rid of the n term. We know that:

Recurrent Formulas of the Generalized Fibonacci Sequences of Third & Fourth Order

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Extending The Sleuth Kit and its Underlying Model for Pooled Storage File System Forensic Analysis

Solutions to Final COMS W4115 Programming Languages and Translators Monday, May 4, :10-5:25pm, 309 Havemeyer

Data Structures and Algorithms. Analysis of Algorithms

The Graphs of Polynomial Functions

EE123 Digital Signal Processing

Analysis of Algorithms

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

IMP: Superposer Integrated Morphometrics Package Superposition Tool

Bezier curves. Figure 2 shows cubic Bezier curves for various control points. In a Bezier curve, only

Creating Exact Bezier Representations of CST Shapes. David D. Marshall. California Polytechnic State University, San Luis Obispo, CA , USA

Lecture 28: Data Link Layer

A Comparative Study of Positive and Negative Factorials

Combination Labelings Of Graphs

Term Project Report. This component works to detect gesture from the patient as a sign of emergency message and send it to the emergency manager.

MAXIMUM MATCHINGS IN COMPLETE MULTIPARTITE GRAPHS

Transcription:

Recursio Recursio Jordi Cortadella Departmet of Computer Sciece Priciple: Reduce a complex problem ito a simpler istace of the same problem Recursio Itroductio to Programmig Dept. CS, UPC 2 Mathematical iductio: example The sum of the first odd umbers is 2 : Recursio is a cocept tightly related to mathematical iductio (typically used for proofs o atural umbers): Proof a base case for the first atural umber Iductive step: proof that validity for also implies validity for +1 (domio effect) Iformal proof: 1 3 5 7 9 2-1 Itroductio to Programmig Dept. CS, UPC 3 Itroductio to Programmig Dept. CS, UPC 4

Mathematical iductio: example Factorial Defiitio of factorial:! = 1 2 2 1 Base case: it works for = 1 Iductive step: let us assume it works for // Pre: 0 // Returs! it factorial(it ) { // iterative solutio it f = 1; for (it i = ; i > 0; --i) f = f i; retur f; Itroductio to Programmig Dept. CS, UPC 5 Factorial Itroductio to Programmig Dept. CS, UPC 6 Factorial: recursive solutio Recursive defiitio: factorial() // Pre: 0 // Returs! 1!, > 0! = ቊ 1, = 0 factorial(-1) factorial(-2) factorial(2) 2 factorial(1) 1-2 -1! it factorial(it ) { // recursive solutio if ( == 0) retur 1; else retur factorial( - 1); Itroductio to Programmig Dept. CS, UPC 7 Itroductio to Programmig Dept. CS, UPC 8

Recursio Geerally, recursive solutios are simpler tha (or as simple as) iterative solutios. There are some problems i which oe solutio is much simpler tha the other. Geerally, recursive solutios are slightly less efficiet tha the iterative oes (if the compiler does ot try to optimize the recursive calls). There are atural recursive solutios that ca be extremely iefficiet. Be careful! Itroductio to Programmig Dept. CS, UPC 9 Recursive desig: termiatio It is ot clear whether the followig fuctio termiates: // Pre: 1 // Returs the umber of steps of the Collatz sequece // that starts with. it Collatz(it ) { // recursive solutio if ( == 1) retur 0; else if (%2 == 0) retur 1 + Collatz(/2); else retur 1 + Collatz(3 + 1); The reaso is that 3 +1 is ot closer to 1 tha Recursive desig: 3 steps 1. Idetify the basic cases i which a simple o-recursive solutio ca be provided. Example: 0! = 1! = 1. 2. Recursive cases: solve the complex cases i terms of simpler istaces of the same problem (domio effect). Example: factorial() = factorial(-1). 3. Termiatio: guaratee that the parameters of the call move closer to the basic cases at each recursive call (the domio chai is ot ifiite). Example: I the case of a factorial, -1 is closer to 0 tha. Therefore, we ca guaratee that this fuctio termiates. Itroductio to Programmig Dept. CS, UPC 10 Recursio: behid the scees... f = factorial(4);... it factorial(it ) 4 if ( 4 <= 1) retur 1; else retur 4 factorial(-1); 3 it factorial(it ) 3 if ( 3 <= 1) retur 1; else retur 3 factorial(-1); 2 it factorial(it ) 2 if ( 2 <= 1) retur 1; else retur 2 factorial(-1); 1 it factorial(it ) 1 if ( 1 <= 1) retur 1; else retur 1 factorial(-1); Itroductio to Programmig Dept. CS, UPC 11 Itroductio to Programmig Dept. CS, UPC 12

Recursio: behid the scees... f = factorial(4); 24... it 24 factorial(it ) 4 if ( 4 <= 1) retur 1; else retur 4 factorial(-1); 24 6 3 it 6 factorial(it ) 3 if ( 3 <= 1) retur 1; else retur 3 factorial(-1); 6 2 2 it 2 factorial(it ) 2 if ( 2 <= 1) retur 1; else retur 2 factorial(-1); 2 1 1 it 1 factorial(it ) 1 if ( 1 <= 1) retur 1; else retur 1 factorial(-1); Recursio: behid the scees Each time a fuctio is called, a ew istace of the fuctio is created. Each time a fuctio returs, its istace is destroyed. The creatio of a ew istace oly requires the allocatio of memory space for data (parameters ad local variables). The istaces of a fuctio are destroyed i reverse order of their creatio, i.e. the first istace to be created will be the last to be destroyed. Itroductio to Programmig Dept. CS, UPC 13 Prit a umber i base b Desig a procedure that prits a umber i base b to cout. Examples: 1024 is 10000000000 i base 2 1101221 i base 3 2662 i base 7 1024 i base 10 Itroductio to Programmig Dept. CS, UPC 14 Prit a umber i base b // Pre: 0, 2 b 10 // Prits the represetatio of i base b void prit_base(it, it b); Basic case: < b oly oe digit. Prit it. Geeral case: b Prit the leadig digits (/b) Prit the last digit (%b) Itroductio to Programmig Dept. CS, UPC 15 Itroductio to Programmig Dept. CS, UPC 16

Write a umber i base b A simpler versio // Pre: 0, 2 b 10 // Prits the represetatio of i base b // Pre: 0, 2 b 10 // Prits the represetatio of i base b void prit_base(it, it b) { if ( < b) cout << ; else { prit_base(/b, b); cout << %b; void prit_base(it, it b) { if ( >= b) prit_base(/b, b); cout << %b; Itroductio to Programmig Dept. CS, UPC 17 Itroductio to Programmig Dept. CS, UPC 18 The puzzle was iveted by the Frech mathematicia Édouard Lucas i 1883. There is a leged about a Idia temple that cotais a large room with three time-wor posts i it, surrouded by 64 golde disks. To fulfil a aciet prophecy, Brahmi priests have bee movig these disks, i accordace with the rules of the puzzle, sice that time. The puzzle is therefore also kow as the Tower of Brahma puzzle. Accordig to the leged, whe the last move i the puzzle is completed, the world will ed. It is ot clear whether Lucas iveted this leged or was ispired by it. (from http://e.wikipedia.org/wiki/tower_of_haoi) Rules of the puzzle: A complete tower of disks must be moved from oe post to aother. Oly oe disk ca be moved at a time. No disk ca be placed o top of a smaller disk. Not allowed! Itroductio to Programmig Dept. CS, UPC 19 Itroductio to Programmig Dept. CS, UPC 20

What rules determie the ext move? How may moves do we eed? There is o trivial iterative solutio. Itroductio to Programmig Dept. CS, UPC 21 Itroductio to Programmig Dept. CS, UPC 22 // Pre: is the umber of disks ( 0). // from, to ad aux are the ames of the pegs. // Post: solves the by movig disks // from peg from to peg to usig peg aux Iductive reasoig: assume that we kow how to solve Haoi for -1 disks Haoi(-1) from left to middle (safe: the largest disk is always at the bottom) Move the largest disk from the left to the right Haoi(-1) from the middle to the right (safe: the largest disk is always at the bottom) Itroductio to Programmig Dept. CS, UPC 23 void Haoi(it, char from, char to, char aux) { if ( > 0) { Haoi( - 1, from, aux, to); cout << Move disk from << from << to << to << edl; Haoi( - 1, aux, to, from); Itroductio to Programmig Dept. CS, UPC 24

// Mai program to solve the // for ay umber of disks it mai() { it Ndisks; // Read the umber of disks ci >> Ndisks; // Solve the puzzle Haoi(Ndisks, L, R, M ); Itroductio to Programmig Dept. CS, UPC 25 > Haoi 5 Move disk from L to M Move disk from M to R Move disk from L to M Move disk from R to L Move disk from L to M Move disk from M to R Move disk from R to L Move disk from M to R Move disk from L to M Move disk from M to R Itroductio to Programmig Dept. CS, UPC 26 Haoi(1,L,R,M) Haoi(1,L,R,M) Haoi(2,L,M,R) L M Haoi(2,L,M,R) Haoi(0,R,L,M) Haoi(2,L,M,R) L M Haoi(0,R,L,M) Haoi(1,R,M,L) R M Haoi(1,R,M,L) R M Haoi(3,L,R,M) Haoi(3,L,R,M) Haoi(1,M,L,R) M L Haoi(1,M,L,R) M L Haoi(2,M,R,L) M R Haoi(0,R,L,M) Haoi(2,M,R,L) Haoi(2,M,R,L) M R Haoi(0,R,L,M) Haoi(1,L,R,M) Haoi(1,L,R,M) Itroductio to Programmig Dept. CS, UPC 27 Itroductio to Programmig Dept. CS, UPC 28

How may moves do we eed for disks? Moves() = 1 + 2 Moves(-1) Moves() 1 1 2 3 3 7 4 15 5 31 6 63 2-1 Let us assume that we ca move oe disk every secod. How log would it take to move disks? time 1 1s 5 31s 10 17m 3s 15 9h 6m 7s 20 12d 3h 16m 15s 25 1y 23d 8h 40m 31s 30 > 34y 40 > 34,000y 50 > 35,000,000y 60 > 36,000,000,000y Itroductio to Programmig Dept. CS, UPC 29 Itroductio to Programmig Dept. CS, UPC 30