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