Title: Week 10 a
1Week 10 - a
- Introduction to Recursion
- Divide and Conquer
2Sample Programs Referenced(code located in
course folder)
- Count the Digits
- Factorial (HANDOUT)
- Fibonacci
- Recursive Exponent
- Paths through a Grid
- TracingRecursion
- Recursive Palindromes
- Divide and Conquer
3Recursion
- Recursion is a basic problem solving technique
that divides a problem into smaller subproblems - These subproblems may also be divided into
smaller subproblems - When the subproblems are small enough to solve
directly the process stops - A recursive algorithm is a problem solution that
has been expressed in terms of two or more easier
to solve subproblems
4Alternate Descriptions ofRecursion
- A programming technique in which a method calls
itself - A different way to look at repetition other than
iteration
5Illegal Recursion
- Recursive Directions--Infinite Recursion
- "Back to the Future"--Infinite Recursion
6Recursion is Mysterious
- You must ass u me that a method already exists as
you are defining it. - "Leap of Faith"
7The Two Requirements
- 1) Base (Stopping) Case
- Recursion stops here
- Missing with Ziggy and Michael J. Fox
- 2) Inductive (Recursive) Case
- Convert to simpler problem
- Also missing with Ziggy and Michael J. Fox
- They call for the same problem again
- Basic structure of a recursive function
- if (base case is reached)
- give solution
- else
- reduce problem to simpler version using recursion
8Counting Digits in n
- Recursive definition
- if n is between 10 and 10
- the number of digits is 1
- otherwise
- the number of digits is 1 more than the number
of digits in n/10 - Example
- digits(321) 1 digits(321/10) 1
digits(32) - 1 1 digits(32/10) 1
1 digits(3) - 1 1 (1)
- 3
9Counting Digits with Java
- public static int numberOfDigits(int n)
-
- if ((-10 lt n) (n lt 10))
- return 1
- else
- return 1 numberOfDigits(n/10)
10Factorial
- Write a function that, given n, computes n!
- n! 1 2 ... (n-1) n
- Example
- 5! 1 2 3 4 5 120
- Specification
- Receive n, an integer.
- Precondition n gt 0
- Return n!, a long (to avoid integer overflow).
11Analysis
- Consider n! 1 2 ... (n-1) n
- but (n-1)! 1 2 ... (n-1)
- substituting n! (n-1)! n
- We have defined the ! function in terms of
itself. - Historically, this is how the function was
defined before computers (and for-loops) existed.
12Base Case
- Recursive functions are designed in a 3-step
process - 1. Identify a base case -- an instance of the
problem whose solution is trivial. - Example The factorial function has two base
cases - if n 0 n! 1
- if n 1 n! 1
13Induction Step
- 2. Identify an induction step -- a means of
solving the non-trivial (or big) instances of
the problem using one or more smaller instances
of the problem. - Example In the factorial problem, we solve the
big problem using a smaller version of the
problem - n! (n-1)! n
- 3. Form an algorithm from the base case and
induction step.
14Algorithm
- // factorial(n)
- Receive n.
- If n lt 1
- return 1.
- Else
- return factorial(n-1) n.
15Factorial Exercise
16factorial in Java
- / factorial(n), defined recursively
- ...
- /
- public static long factorial(int n)
- if (n lt 1)
- return 1 // stopping condition
- else
- return factorial(n-1) n // inductive step
- // end of factorial method
17Fibonacci Numbers
- Fibonacci series (of integers) occurs frequently
in nature as the growth rate for certain
idealized animal populations - The series begins with 0 and 1, and each
successive number is the sum of the two previous
numbers - Fib(0) 0, Fib(1) 1, Fib(n) Fib(n-2)
Fib(n-1) - 0, 1, 1, 2, 3, 5, ?
- Base case(s)?
- Recursive (inductive) step?
- Review and try in BlueJ
18Fibonacci Sequence
- 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
public static int fib(int n) // precondition
n gt 0 if (n lt 2) return n else
return fib(n-1) fib(n-2) // end of fib
function
19Math.pow(x,n) method
- Write a recursive algorithm to calculate the nth
power of x - x x x x x (n times)
- Base case?
- what condition?
- return what?
- Inductive step?
- what simpler call to the same function?
20Evaluating Exponents Recursively
- static int power(int x, int n)
- // raise x to the power n
- // precondition n gt 0
- if (n 0)
- return 1
- else
- return x power(x, n 1)
- // end of power function
21Paths through a Grid"Lost in Manhattan" (1 of 3)
46th Street
7th Avenue
45th Street
5th Avenue
6th Avenue
44th Street
43rd Street
42nd Street
North North North North East East East North
North East North North
22Paths through a Grid"Lost in Manhattan" (2 of 3)
- Two choices at each intersection
- North or East
- Start at myRow, myCol (42,7)
- Want to get to dinerRow, dinerCol (46,5)
- method is to determine total number of different
paths one could take
23Paths through a Grid"Lost in Manhattan" (3 of 3)
- Total number of paths number if started going
East plus number if started going North - If we started by going north one block, we would
now be dealing with simpler problem - Problem keeps getting simpler until we are
looking down the street or avenue and see the
Diner (i.e. we reach the correct row or column) - There is now only one path without going the
wrong direction
24Paths Program
- Constructor sets up destination row and column
(target) - Loop to allow user to enter starting location
(row col) - Run in BlueJ
- Look at Code
25Java BREAK
26Pushdown Stack
- Stack is a data structure
- First In, Last Out (like cafeteria trays)
- Stack used to automatically track info for
function calls - return addresses
- call-by-value parameters
- local variables
- Every time a function is called, a set of data
goes on the stack, it disappears when the
function returns - Recursion the stack grows
27Recursion ClassContains Several Sample Methods
- public static int numberOfDigits( int n )
- // counts the number of digits in a whole number
- public static int numberOfDigits( int n )
- // counts the number of digits in a whole number
- public static int numberOfDigitsInf( int n )
- // calculates traces the factorial of a number
- public static long factorial( int n )
- // calculates x raised to the n power
- public static long power( int x, int n )
- // calculates x raised to the n power more
efficiently - public static long power2( int x, int n)
- public static void printReverse(String s)
28Tracing Recursion
- Could we add print statements to method to have
it trace the process? - What would be printed by the following?
- public static int numberofDigits(int n)
-
- System.out.println("--gt n is " n)
- if ((-10 lt n) (n lt 10))
- return 1
- else
- return 1 numberofDigits(n/10)
29Tracing Recursion
- How do we trace the upward spiral?
- See Recursion Project
- Note numberOfDigitsTrace method in Recursive
class - print statements when enter and before returns
- need to compute the return value separate from
the return statement - could we put the print after the return? why/why
not? - What should be printed?
- Try it
30Review the 2 Requirements
- 1) Base (Stopping) Case
- Recursion stops here
- 2) Inductive (Recursive) Case
- Convert to simpler problem
- Basic structure of a recursive function
- if (base case is reached)
- give solution
- else
- reduce problem to simpler version using recursion
What happens if we forget to include the base
case?
31Infinite Recursion
- If we have no simple case that just returns a
value instead of calling the method again, could
we create an infinite loop? - What would the following code do?
- public static int numberOfDigitsInf( int n )
-
- System.out.println("--gt n is " n)
- int returnValue 1 numberOfDigitsInf( n/10
) - System.out.println("lt-- Returning "
returnValue) - return returnValue
- // end numberOfDigitsInf
- Try it in the project does it ever return
anything? - Wait until stack overflows
32Strings and Recursion
- Write a recursive algorithm for printing a string
in reverse order - Base case?
- Recursive (inductive) step?
- Try it in Recursion project
- Note implicit use of a "Stack"
33Palindromes(review)
- AHA! BOB MOM DAD
- KAYAK
- RADAR
- SOLOS
- DEIFIED
- A TOYOTA
- BIRD RIB
- DON'T NOD
- GNU DUNG
- RACE CAR
- TOP SPOT
- DAMMIT, I'M MAD!
- "MADAM, I'M ADAM" (said to Eve in Garden of Eden)
- WONTONS? NOT NOW.
- RACE FAST, SAFE CAR.
- NEVER ODD OR EVEN
- DENNIS AND EDNA SINNED
- STEP ON NO PETS
- WAS IT A CAT I SAW?
- TOO HOT TO HOOT!
- NOT NEW YORK, ROY WENT ON
- A SLUT NIXES SEX IN TULSA
- MA IS AS SELFLESS AS I AM
- A MAN, A PLAN, A CANAL PANAMA
- CIGAR? TOSS IT IN A CAN, IT IS SO TRAGIC.
34Palindromes
- A palindrome is a string that reads the same
forwards and backwards - e.g. radar or 1991 or ab cdc ba
- How could we use recursion to test to see if a
string is a palindrome? - Base case?
- Recursive (inductive) step?
- Write an algorithm
- Trace it by hand with the examples above and with
a non-palindrome? - Implement the algorithm in Java
- Review and try in Recursion project
35Divide and Conquer
- Using this method, each recursive subproblem is
about one-half the size of the original problem - If we could define power so that each subproblem
was based on computing kn/2 instead of kn 1 we
could use the divide and conquer principle - Recall the efficiency of Binary Search vs. Linear
- Recursive divide and conquer algorithms are often
more efficient than iterative algorithms
36Evaluating Exponents UsingDivide and Conquer
- static int power(int x, int n)
- if (n 0)
- return 1
- else
- int t power(x, n/2)
- if ((n 2) 0)
- return t t
- else
- return x t t
- // end of divide conquer power
37HW Assignment 9Prefix Notation
- In prefix notation, operators are followed by
their two operands. (e.g. 12 3 is interpreted
as 123) - Your program must use recursion to allow nested
expressions with multiple operators. - Note that the order of execution can be specified
without use of parentheses. - See examples on next slide
38HW Assignment 92 "Volunteers" to Board
(odd/even problems)
- 5 / 3 2
- 2 3 5 7
- 12345
- 123 456
- 2 3 5 7 1
- 2 3 4 5
- 1 2 3 4 5 6
- / 8 / 4 2
39HW Assignment 92 "Volunteers" to Board
(odd/even problems)
- 5 / 3 2 6.5
- 2 3 5 7 210.0
- 12345 12345.0
- 123 456 579.0
- 2 3 5 7 1 18.0
- 2 3 4 5 26.0
- 1 2 3 4 5 6 21.0
- / 8 / 4 2 4.0
40HW Assignment 9main Method
- public static void main(String args)
- String expression
- StringBuffer expBuffer
- double result
- while (true)
- expression JOptionPane.showInputDialog(
- "Please enter a Polish
Expression") - expBuffer new StringBuffer(expression)
- if (expression.equals("")) break
- result eval(expBuffer)
- System.out.println(expression " "
result) - // end of input loop
- // end of main method
41HW Assignment 9Sample Run
- Run instructor's version of HW 9
- You will be modifying the code to read all
expressions from an external file
42Java BREAK