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

Similar documents
Backtracking. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. Chapter 5

Backtracking. Module 6. The Eight Queens Problem. CS 147 Sam Houston State University Dr. McGuire. Backtracking. Recursion Revisited

Chapter 2. Question 2 Write a box trace of the function given in Checkpoint Question 1. We trace the function with 4 as its argument (see next page).

Lecture Chapter 6 Recursion as a Problem Solving Technique

What is Recursion? ! Each problem is a smaller instance of itself. ! Implemented via functions. ! Very powerful solving technique.

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

Recursion as a Problem-Solving Technique. Chapter 5

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

Programming with Recursion. What Is Recursion?

Solving problems by recursion

Recursion continued. Programming using server Covers material done in Recitation. Part 2 Friday 8am to 4pm in CS110 lab

8/22/12. Outline. Backtracking. The Eight Queens Problem. Backtracking. Part 1. Recursion as a Problem-Solving Technique

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

1 Recursion. 2 Recursive Algorithms. 2.1 Example: The Dictionary Search Problem. CSci 235 Software Design and Analysis II Introduction to Recursion

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

Unit-2 Divide and conquer 2016

Recursion: The Mirrors. (Walls & Mirrors - Chapter 2)

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

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

CSC 273 Data Structures

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?


DATA ABSTRACTION AND PROBLEM SOLVING WITH JAVA

CS200: Recursion and induction (recap from cs161)

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

Recursion. Recursion is: Recursion splits a problem:

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

EE 368. Weeks 4 (Notes)

Functions and Recursion

CS302 - Data Structures using C++

CmpSci 187: Programming with Data Structures Spring 2015

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

This book is licensed under a Creative Commons Attribution 3.0 License

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

University of the Western Cape Department of Computer Science

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

DEEPIKA KAMBOJ UNIT 2. What is Stack?

Operators. Java operators are classified into three categories:

Chapter 18 Recursion. Motivations

Recursion. Chapter 7

Recursive Definitions

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015

Structured Programming with C Wrap-up

Algorithms COMBINATORIAL SEARCH. permutations backtracking counting subsets paths in a graph

Classic Data Structures Introduction UNIT I

Recursion. Example R1

Lecture 8 Recursion. The Mirrors

Tribhuvan University Institute of Science and Technology Computer Science and Information Technology (CSC. 154) Section A Attempt any Two questions:

Introduction to Computers & Programming

Sorting & Searching (and a Tower)

INSTITUTE OF AERONAUTICAL ENGINEERING

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU

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

Recursion vs Induction

Data Structures and Algorithms Notes

Chapter 15: Recursion

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

CSE 214 Computer Science II Recursion

Recursion. Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

Recursion vs Induction. CS3330: Algorithms The University of Iowa

DIVIDE & CONQUER. Problem of size n. Solution to sub problem 1

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

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

1. (a) O(log n) algorithm for finding the logical AND of n bits with n processors

Objectives. Recursion. One Possible Way. How do you look up a name in the phone book? Recursive Methods Must Eventually Terminate.

Table of Contents. Chapter 1: Introduction to Data Structures... 1

Recursion. Chapter 5

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

QUIZ. 0] Define arrays 1] Define records 2] How are arrays and records: (a) similar? (b) different?

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

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

G Programming Languages - Fall 2012

Formal Languages and Automata Theory, SS Project (due Week 14)

Bachelor Level/ First Year/ Second Semester/ Science Full Marks: 60 Computer Science and Information Technology (CSc. 154) Pass Marks: 24

CS 211: Recursion. Chris Kauffman. Week 13-1

CS/CE 2336 Computer Science II

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

Prefix/Infix/Postfix Notation

= otherwise W-4 W-1. Overview. CSE 142 Computer Programming I. Overview. Factorial Function

Recursion. Dr. Jürgen Eckerle FS Recursive Functions

Lecture 6: Recursion RECURSION

CS 151. Recursion (Review!) Wednesday, September 19, 12

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

1.7 Recursion. Department of CSE

March 13/2003 Jayakanth Srinivasan,

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

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

O(n): printing a list of n items to the screen, looking at each item once.

SECTION 5.1. Sequences

Functions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

Tutorial 3: Infix, Prefix, Postfix & Tower of Hanoi

We cover recursion in 150. Why do it again in 151?

CS302 Data Structures using C++

Recursion. notes Chapter 8

- Wikipedia Commons. Intro Problem Solving in Computer Science 2011 McQuain

Transcription:

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

Recursion Solution 3 RECURSION SOLUTION Recursion An extremely powerful problem-solving technique Breaks a problem in smaller identical problems An alternative to iteration o An iterative solution involves loops Some recursion solutions are inefficient and impractical 2

RECURSION SOLUTION Looking up a word in a dictionary Sequential search o Starts at the beginning of the collection o Looks at every item in the collection in order until the item being searched for is found Binary search o Repeatedly halves the collection and determines which half could contain the item o Uses a divide and conquer strategy Search dictionary Search first half of dictionary Search second half of dictionary RECURSION SOLUTION Facts about a recursive solution search (in thedictionary:dictionary, in aword:string) { if(thedictionary is one page in size){ scan the page for aword else{ Open the Dictionary to a point near the middle Determine which half of the thedictionary contains aword if(aword is in the first half){ search(first half of thedictionary, aword) else{ search(second half of thedictionary, aword) one of the smaller problems must be the base case A test for the base case enables the recursive calls to stop A recursive method calls itself Each recursive call solves an identical, but smaller, problem 3

RECURSION SOLUTION Four questions for construction recursive solutions How can you define the problem in terms of a smaller problem of the same type? How does each recursive call diminish the size of the problem? What instance of the problem can serve as the base case? As the problem size diminishes, will you reach this base case? RECURSION SOLUTION A Recursive Valued Method: The Factorial of n Problem o Compute the factorial of an integer n An iterative definition of factorial(n) factorial(n) = n * (n-1) * (n-2) * * 1 for any integer n > 0 factorial(0) = 1 A recursive definition of factorial(n) factorial(n) = 1 if n = 0 n * factorial(n-1) if n > 0 4

RECURSION SOLUTION A Recursive Valued Method: The Factorial of n public static int fact (int n){ //----------------------------------------------------------------- //precondition: n must be greater than or equal to 0 //postcondition: returns the factorial of n //----------------------------------------------------------------- if(n==0){ return 1; else{ return n*fact(n-1); RECURSION SOLUTION Box trace A systematic way to trace the actions of a recursive method Each box roughly corresponds to an activation record An activation record o Contains a method s local environment at the time of calling and as a result of the call to the method A method s local environment includes: o The method s local variables o A copy of the actual value arguments o A return address in the calling routine o The value of the method itself System.out.println(fact(3)); 5

RECURSION SOLUTION A Recursive void Method: Writing a String Backward Problem o Given a string of characters, write it in reverse order Recursive solution o Each recursive step of the solution diminishes by 1 the length of the string to be written backward Base case o Write the empty string backward Recursively: o Strip away the last character or the first character RECURSION SOLUTION A Recursive void Method: Writing a String Backward Strip away the last character or the first character writebackward (in s:string){ if(the string s is empty){ Do nothing else{ writebackward(s the last character minus of its s first character) writebackward(s the first character minus of its s last character) 6

Counting Things 13 COUNTING THINGS Next three problems Require you to count certain events or combinations of events or things Contain more than one base cases Are good examples of inefficient recursive solutions 7

COUNTING THINGS Multiplying Rabbits (The Fibonacci Sequence) Facts about rabbits o Rabbits never die o A rabbit reaches sexual maturity exactly two months after birth, that is, at the beginning of its third month of life o Rabbits are always born in male-female pairs Problem At the beginning of every month, each sexually mature male-female pair gives birth to exactly one male-female pair o How many pairs of rabbits are alive in month n? Recursive definition rabbit(n) = 1 if n is 1 or 2 rabbit(n-1) + rabbit(n-2) if n > 2 COUNTING THINGS Multiplying Rabbits (The Fibonacci Sequence) 8

COUNTING THINGS Organizing a Parade Rules about organizing a parade o The parade will consist of bands and floats in a single line o One band cannot be placed immediately after another Problem o How many ways can you organize a parade of length n? COUNTING THINGS Organizing a Parade Let: o P(n) be the number of ways to organize a parade of length n o F(n) be the number of parades of length n that end with a float o B(n) be the number of parades of length n that end with a band o Then, P(n) = F(n) + B(n) Number of acceptable parades of length n that end with a float F(n) = P(n-1) Number of acceptable parades of length n that end with a band B(n) = F(n-1) Number of acceptable parades of length n P(n) = P(n-1) + P(n-2) 9

COUNTING THINGS Organizing a Parade Base cases o P(1) = 2 (The parades of length 1 are float and band.) o P(2) = 3 (The parades of length 2 are float-float, band-float, and float-band.) Solution o P(1) = 2 o P(2) = 3 o P(n) = P(n-1) + P(n-2) for n > 2 COUNTING THINGS Mr. Spock s Dilemma (Choosing k out of n Things) Problem o How many different choices are possible for exploring k planets out of n planets in a solar system? o Let c(n, k) be the number of groups of k planets chosen from n In terms of Planet X: o c(n, k) = (the number of groups of k planets that include Planet X) + (the number of groups of k planets that do not include Planet X) o c(n, k) = c(n-1, k-1) + c(n-1, k) Recursive solution 1 if k = 0 c(n, k) = 1 if k = n 0 if k > n c(n-1, k-1) + c(n-1, k) if 0 < k < n 10

COUNTING THINGS Mr. Spock s Dilemma (Choosing k out of n Things) Searching an Array 22 11

SEARCHING AN ARRAY A high-level binary search binarysearch(in anarray:arraytype, in value:itemtype){ if (anarray is of size 1) { Determine if anarray s item is equal to value else { Find the midpoint of anarray Determine which half of anarray contains value if (value is in the first half of anarray) { binarysearch (first half of anarray, value) else { binarysearch(second half of anarray, value) // end if // end if SEARCHING AN ARRAY A high-level binary search Implementation issues: o How will you pass half of anarray to the recursive calls to binarysearch? o How do you determine which half of the array contains value? o What should the base case(s) be? Given value is in or not in the array o How will binarysearch indicate the result of the search? 12

SEARCHING AN ARRAY Finding the k th Smallest Item in an Array The recursive solution proceeds by: 1. Selecting a pivot item in the array 2. Cleverly arranging, or partitioning, the items in the array about this pivot item 3. Recursively applying the strategy to one of the partitions SEARCHING AN ARRAY Finding the k th Smallest Item in an Array Let: ksmall(k, anarray, first, last) = k th smallest item in anarray[first..last] Solution: ksmall(k, anarray, first, last) ksmall(k, anarray, first, pivotindex-1) if k < pivotindex first + 1 = p if k = pivotindex first + 1 ksmall(k-(pivotindex-first+1), anarray, pivotindex+1, last) if k >pivotindex first+ 1 13

Organizing Data 28 ORGANIZING DATA The Towers of Hanoi The emperor s puzzle: n disks and three poles o A (the source), B (the destination), and C (the spare) o The disks were of different sizes and had holes in the middle o The disks could be placed only on top of disks larger than themselves o Initially, all the disks were on pole A o The puzzle was to move the disks, one by one, from pole A to pole B. 14

ORGANIZING DATA The Towers of Hanoi ORGANIZING DATA The Towers of Hanoi Pseudocode solution solvetowers(count, source, destination, spare) if (count is 1) { Move a disk directly from source to destination else { solvetowers(count-1, source, spare, destination) solvetowers(1, source, destination, spare) solvetowers(count-1, spare, destination, source) //end if 15

ORGANIZING DATA The Towers of Hanoi Recursion and Efficiency 33 16

RECURSION AND EFFICIENCY Recursion powerful-solving technique that often produces very clean solutions to even the most complex problems. Simple, short implementation Some recursive solutions are so inefficient that they should not be used Factors that contribute to the inefficiency of some recursive solutions Overhead associated with method calls Inherent inefficiency of some recursive algorithms Backtracking 35 17

BACKTRACKING Backtracking Considering an organized way to make successive guesses at a solution. If a particular guess leads to a dead end, you back up to that guess and replace it with a different guess. A strategy for guessing at a solution and backing up when an impasse is reached BACKTRACKING The Eight Queens Problem Problem o Place eight queens on the chessboard so that no queen can attack any other queen Strategy: guess at a solution There are C(64,8) = 4,426,165,368 ways to arrange 8 queens on a chessboard of 64 squares An observation that eliminates many arrangements from consideration o No queen can reside in a row or a column that contains another queen Now: only 8!=40,320 arrangements of queens to be checked for attacks along diagonals 18

BACKTRACKING The Eight Queens Problem Providing organization for the guessing strategy o Place queens one column at a time o If you reach an impasse, backtrack to the previous column BACKTRACKING The Eight Queens Problem A recursive algorithm that places a queen in a column Base case o If there are no more columns to consider You are finished Recursive step o If you successfully place a queen in the current column Consider the next column o If you cannot place a queen in the current column You need to backtrack 19

Defining Language 40 DEFINING LANGUAGE Two Simple Languages: Palindromes A string that reads the same from left to right as it does from right to left Examples: radar, deed Language o Palindromes = {w : w reads the same left to right as right to left Grammar o < pal > = empty string < ch > a < pal > a b < pal > b Z < pal > Z o < ch > = a b z A B Z 20

DEFINING LANGUAGE Two Simple Languages: Palindromes Recognition algorithm ispal(w) if (w is the empty string or w is of length 1) { return true else if (w s first and last characters are the same letter ) { return ispal(w minus its first and last characters) else { return false DEFINING LANGUAGE Two Simple Languages: Strings of the form A n B n The string that consists of n consecutive A s followed by n consecutive B s Language o L = {w : w is of the form A n B n for some n 0 Grammar o < legal-word > = empty string A < legal-word > B 21

DEFINING LANGUAGE Two Simple Languages: Strings of the form A n B n Recognition algorithm isanbn(w) if (the length of w is zero) { return true else if (w begins with the character A and ends with the character B) { return isanbn(w minus its first and last characters) else { return false DEFINING LANGUAGE Two Simple Languages: Strings of the form A n B n Recognition algorithm isanbn(w) if (the length of w is zero) { return true else if (w begins with the character A and ends with the character B) { return isanbn(w minus its first and last characters) else { return false 22

DEFINING LANGUAGE Algebraic expression Infix expressions o An operator appears between its operands o Example: a + b*c Prefix expressions o An operator appears before its operands o Example: + a* bc Postfix expressions o An operator appears after its operands o Example: a bc* + DEFINING LANGUAGE Algebraic expression To convert a fully parenthesized infix expression to a prefix form o Move each operator to the position marked by its corresponding open parenthesis o Remove the parentheses Example o Infix expression: ((a + b) * c o Prefix expression: * + a b c 23

DEFINING LANGUAGE Algebraic expression To convert a fully parenthesized infix expression to a postfix form o Move each operator to the position marked by its corresponding closing parenthesis o Remove the parentheses Example o Infix form: ((a + b) * c) o Postfix form: a b + c * DEFINING LANGUAGE Algebraic expression To avoid ambiguity, infix notation normally requires o Precedence rules o Rules for association o Parentheses Prefix and postfix expressions o Never need Precedence rules Association rules Parentheses o Have Simple grammar expressions Straightforward recognition and evaluation algorithms 24

DEFINING LANGUAGE Algebraic expression Prefix expression o < prefix > = < identifier > < operator > < prefix > < prefix > o < operator > = + - * / o < identifier > = a b z Postfix expression o < postfix > = < identifier > < postfix > < postfix > < operator> o < operator > = + - * / o < identifier > = a b z Fully parenthesized expressions o < infix > = < identifier > (< infix > < operator > < infix > ) o < operator > = + - * / o < identifier > = a b z HOMEWORK Read through Chapter 3, Chapter 6 25