Recursion. Dr. Jürgen Eckerle FS Recursive Functions

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

Recursive Definitions

mith College Computer Science Week 13 CSC111 Spring 2018 Dominique Thiébaut

Recursion. Jordi Cortadella Department of Computer Science

UNIT 5A Recursion: Basics. Recursion

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

CSC-140 Assignment 4

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )

UNIT 5A Recursion: Basics. Recursion

Algorithm. Building blocks of algorithm

Algorithmic Methods Tricks of the Trade

SECTION 5.1. Sequences

Lecture 24 Tao Wang 1

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 5. The Towers of Hanoi. Divide and Conquer

Summary. csci 210: Data Structures Recursion. Recursive algorithms. Recursion. Topics READING:

csci 210: Data Structures Recursion


Recursive Thinking. Chapter 8: Recursion. Recursive Definitions. Recursion. Java Software Solutions for AP* Computer Science A 2nd Edition

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

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

Divide & Conquer. 2. Conquer the sub-problems by solving them recursively. 1. Divide the problem into number of sub-problems

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion

Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank

Recursion. move(64, 1, 2, 3);

Lecture 6: Recursion RECURSION

Recursion Introduction OBJECTIVES

Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

12/30/2013 S. NALINI,AP/CSE

Chapter 10: Recursive Problem Solving

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

Unit-5 Dynamic Programming 2016

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Recursive Sequences. Lecture 24 Section 5.6. Robb T. Koether. Hampden-Sydney College. Wed, Feb 26, 2014

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

Reading 8 : Recursion

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Bisection method. we can implement the bisection method using: a loop to iterate until f(c) is close to zero a function handle to the function f

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

Goals: Define computational problem instance of a computational problem algorithm pseudocode Briefly discuss recursive procedure big-o notation

SOFTWARE DEVELOPMENT 1. Recursion 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Lecture 6,

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

Induction and Recursion. CMPS/MATH 2170: Discrete Mathematics

Programming and Data Structure

Recursion. Chapter 2. Objectives. Upon completion you will be able to:

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

Recursive Helper functions

CSE 214 Computer Science II Recursion

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ).

Reduction & Recursion Overview

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

! New mode of thinking. ! Powerful programming paradigm. ! Mergesort, FFT, gcd. ! Linked data structures.

Recursive Sequences. Lecture 24 Section 5.6. Robb T. Koether. Hampden-Sydney College. Wed, Feb 27, 2013

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSE 2123 Recursion. Jeremy Morris

recursive algorithms 1

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

Data Structures And Algorithms

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

CS Data Structures and Algorithm Analysis

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

Lecture P6: Recursion

6.001 Notes: Section 4.1

CSE Data Structures and Introduction to Algorithms... In Java! Instructor: Fei Wang. Mid-Term Exam. CSE2100 DS & Algorithms 1

CSC 8301 Design and Analysis of Algorithms: Recursive Analysis

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

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

CMSC Introduction to Algorithms Spring 2012 Lecture 16

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

PSD1A. DESIGN AND ANALYSIS OF ALGORITHMS Unit : I-V

Computer Science 385 Analysis of Algorithms Siena College Spring Topic Notes: Divide and Conquer

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

CSC 505, Spring 2005 Week 6 Lectures page 1 of 9

Lecture 6: Combinatorics Steven Skiena. skiena

Recursion. Thinking Recursively. Tracing the Recursive Definition of List. CMPT 126: Lecture 10. Recursion

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series.

11. Recursion. n (n 1)!, otherwise. Mathematical Recursion. Recursion in Java: Infinite Recursion. 1, if n 1. n! =

2.3 Recursion 7/23/2015 3:06:35 PM

12. Recursion. n (n 1)!, otherwise. Educational Objectives. Mathematical Recursion. Recursion in Java: 1, if n 1. n! =

Recursive Algorithms II

Finite Automata Theory and Formal Languages TMV027/DIT321 LP4 2018

Recursion Chapter 4 Self-Reference. Recursive Definitions Inductive Proofs Implementing Recursion

Effective CNF Encodings for the Towers of Hanoi

The Knapsack Problem an Introduction to Dynamic Programming. Slides based on Kevin Wayne / Pearson-Addison Wesley

Central Europe Regional Contest 2016

26 How Many Times Must a White Dove Sail...

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

Algorithm Design Techniques. Hwansoo Han

Kent State University

Backtracking. Examples: Maze problem. The bicycle lock problem: Consider a lock with N switches, each of which can be either 0 or 1.

Index. Anagrams, 212 Arrays.sort in O(nlogn) time, 202

Overview. What is recursion? When one function calls itself directly or indirectly.

Solutions to Problem 1 of Homework 3 (10 (+6) Points)

The Citizen s Guide to Dynamic Programming

EE 368. Weeks 4 (Notes)

Recursion (Part 2) 1

Recursion. notes Chapter 8

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages

Introduction to Computers & Programming

Transcription:

Recursion Dr. Jürgen Eckerle FS 2008 Recursive Functions Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition. For example: n! = n (n-1)! 1

Recursive Functions Recursion, The term is also used more generally to describe a process of repeating objects in a self-similar way. For instance, when the surfaces of two mirrors are almost parallel with each other the nested images that occur are a form of recursion. Recursive Functions 2

Recursive Functions Recursive Functions In mathematics and computer science, recursion specifies (or constructs) a class of objects or methods (or an object from a certain class) by defining a few very simple base cases or methods (often just one), and then defining rules to break down complex cases into simpler cases. 3

Recursive Functions For example, the following is a recursive definition of person's ancestors: One's parents are one's ancestors (base case); The parents of any ancestor are also ancestors of the person under consideration (recursion step). Recursive Functions It is convenient to think that a recursive definition defines objects in terms of "previously defined" objects of the class to define. Definitions such as these are often found in mathematics. For example, the formal definition of natural numbers in set theory is: 1 is in N ifnis in N, then n + 1 is in N The set of natural numbers is the smallest set satisfying the previous two properties. 4

Recursive Functions How to implement a recursive function? Example: fak(0) = 1. fak(n) = n fak(n-1), n > 0. This function can be implemented both by a recursively or iteratively (not always practical). Implementation by a recursive function is often a straighforward approach, but... consider the recursion tree (reflecting the calling hierarchy). Recursive Functions Fibonacci numbers fib(1) = 1 fib(2) = 1 fib(n) = fib(n-1) + fib(n-2), n > 2 How to implement? Recursively, but... 5

Recursive Functions Recursive Functions Ackermann function Definition: A(0, m) = m + 1 A(n+1, 0) = A(n, 1) A(n+1, m+1) = A(n, A(n+1, m)) Termination? 6

Recursive Functions Koch curve three iteration steps Recursive Functions After five iteration steps 7

Koch snowflake Recursive Functions Recursive Functions A Sierpinski triangle: a confined recursion of triangles to form a geometric lattice. 8

Recursive Functions The Efficiency of Recursion Occasionally, a recursive solution runs much slower than its iterative counterpart In most cases, the recursive solution is only slightly slower, because Each recursive method call takes a certain amount of processor time Smart compilers can avoid recursive method calls if they follow simple patterns, but most compilers don't do that In many cases, a recursive solution is easier to understand and implement correctly than an iterative solution. "To iterate is human, to recurse divine.", L. Peter Deutsch Recursive Functions Exercises Implement a method which computes all permutations of a given sequence. Implement a method which checks whether a given string is a palindrome. 9

Divide & Conquer Idea: Divide a given (complex) problem into a set of smaller problems and solve these and merge them to a complete solution. If the smaller problems have the same structure as the originally problem, this problem solving process can be applied recursively. This problem solving process stops as soon as trivial problems are reached which can be solved in one step. Divide & Conquer Method: If the problem P is trivial, solve it. Otherwise: [Divide] Divide P into a set of smaller problems P[0],..., P[n-1]. [Conquer] Compute a solution S[i] of all the subproblems P[i]. [Merge] Merge all the subsolutions S[i] to a solution S of P. 10

Divide & Conquer The Tower of Hanoi or Towers of Hanoi is a mathematical game or puzzle. It consists of three pegs, and a number of disks of different sizes which can slide onto any peg. The puzzle starts with the disks neatly stacked in order of size on one peg, smallest at the top, thus making a conical shape. Divide & Conquer 11

Divide & Conquer The objective of the game is to move the entire stack to another peg, obeying the following rules: Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the pegs and sliding it onto another peg, on top of the other disks that may already be present on that peg. No disk may be placed on top of a smaller disk. Divide & Conquer Origin: The puzzle was invented by the French mathematician Édouard Lucas in 1883. There is a legend about an Indian temple which contains a large room with three time-worn posts in it surrounded by 64 golden disks. The priests of Brahma, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the rules of the puzzle. According to the legend, when the last move of the puzzle is completed, the world will end. The puzzle is therefore also known as the Tower of Brahma puzzle. It is not clear whether Lucas invented this legend or was inspired by it. 12

Divide & Conquer Recursive algorithm Label the pegs A, B, C; these labels may move at different steps; Let n be the total number of disks; number the disks from 1 (smallest, topmost) to n (largest, bottommost). To move n disks from peg A to peg B: Moven 1 disks from A to C. This leaves the nth disk alone on peg A; Move the nth disk from A to B; Moven 1 disks from C to B so they sit on the nth disk. Divide & Conquer Exercise Problem: Given a set S of coins (weights) and a value x. Decide, whether there is a subset of S whose values added together yields exactly x. Implement a method which checks for a given set of coins and a value x, whether the sum of a subset of coins is x. If this is the case, the method returns this subset of coins. 13

Divide & Conquer Given a sequence X: x[1],..., x[n]. Is the decomposition problem solvable for X? Problem P(i,j): Is there a subsequence of x[1],..., x[i]., whose sum is j? Solution of P(i,j): A bit vector (b[1],..., b[i]) where b[1]*x[1] +... + b[i]*x[i] = j. D&C-approach: P(i,j) is solvable if and only if P(i-1,j) is solvable or P(i-1,j-x[i]) is solvable. 14

15

Backtracking Backtracking is universal solving method. The solution method generates systematically all the possible alternatives and checks whether a solution has been found (brute-force approach). It is applied to a lot of problems, where no better solution is known. Backtracking 16

Backtracking A subproblem or subsolution can described by a vector (of integers). A given subsolution is extended in the forward step. The forward steps is applied until a solution is found or you can decide that the given subsolution cannot be extended to a complete solution (decided by a consistency condition). In the latter case go back to the last point where a new decision can be made (backward step). Backtracking Assumptions: A solution is given by (x[1], x[2],..., x[n]), where n ==k. A goal condition P[n] is fulfilled, if and only if (x[1],..., x[n]) is a solution, that is P[n](x[1], x[2],..., x[n]) is true gdw (x[1], x[2],..., x[n]) is a solution. A test P[k] decides whether (x[1],..., x[k]) is inconsistent and can be extended to a solution. Additionally: If P[k](x[1],..., x[k+1]) is fulfilled, then P[k](x[1],..., x[k]) is also fulfilled. As a result: If P[k](x[1],..., x[k]) is not fulfilled, then P[k+1](x[1],..., x[k], x[k+1]) is also not fulfilled. The set of elements x[k+1] extending (x[1],..., x[k]) in a consistent way, denoted by S[k](x[1],..., x[k]) or shortly S[k], is finite. 17

Backtracking Start step: Start with an empty tuple ( ). Forward step: If (x[1],..., x[k]) is not a solution, extend it by adding a new element of S[k], that is add x[k+1] such that the consistency condition P[k+1](x[1],..., x[k+1]) is fulfilled. Backward step: If all extensions of (x[1],..., x[k]) does not yield a solution, then go back to (x[1],..., x[k-1]) and select a new element x[k] of S[k-1]. Backtracking Exercises Give a recursive function which applies the backtracking algorithm. Implement a method which solves Sudoku puzzles. Implement a method which merges a set of partial ordering to a total ordering, for example, {A<D, D<F} and {B<C, C<D} yield {A<B, B<C, C<D, D<F}. 18

Backtracking /** precondition: P[k](x[1],..., x[k]) is true postcondition: The search tree rooted at (x[1],..., x[k]) is traversed @return true if (x[1],..., x[k]) is a solution, false otherwise */ boolean FoundSolution(x[1], x[2],..., x[k]){ found = false;... //traverse the tree rooted at (x[1],..., x[k]) return found; } boolean FoundSolution(x[1], x[2],..., x[k]){ found = false; Compute S[k]; //the extensions fulfilling the consistency condition While (S[k] is not empty AND found = false) { Select x[k+1] of S[k]; Delete x[k+1] in S[k]; if (n == k+1){ //(x[1],, x[k], x[k+1]) is a solution Print the solution; found = true; } else { //search on found = FoundSolution(x[1],..., x[k], x[k+1]); if (!found) { restore; //only necessary if the tuple //is given by reference } } return found; } } 19

Recursive Functions Partition Problem We have a set S: x[1],..., x[n] of positive integers. Is there a partition of S into two subsets S[1] and S[2] such that the sums of the elements of S[1] and S[2] are equal? 20