Week11
- 2. © 2004 Pearson Addison-Wesley. All rights reserved 5-2
Copyright Warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been copied and communicated to you by or
on behalf of Bond University pursuant to Part VB of the
Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright
under the Act. Any further copying or communication of this
material by you may be the subject of copyright protection
under the Act.
Do not remove this notice.
- 3. © 2004 Pearson Addison-Wesley. All rights reserved 5-3
What is Recursion?
• Recursion is a technique, which is used to solve a
specific class of problems
• With these type of problems:
You can solve one part of the problem, and
This leaves a smaller problem which is exactly the same
type as the original problem
• 99% of problems do not need recursion.
• However, 1% of problems do need recursion!
• The hardest part of recursion is how to visualise a
problem and see how we can apply the recursion
technique
• Hint: if you are asked to do something recursively,
it can be done that way. Try to visualise how
- 4. © 2004 Pearson Addison-Wesley. All rights reserved 5-4
What Problems Can Use Recursion?
• In order to solve a problem with recursion, you
need 3 things to be true:
1 Given a problem, you can solve part of the problem
immediately
2 This leaves a smaller problem of exactly the same type
3 There is a “base case”, i.e. a simplest problem, which can
be solved without step 2.
• Step 2 is the “recursion” part of the problem
solving
• Let's have a look at a game which uses recursion
- 5. © 2004 Pearson Addison-Wesley. All rights reserved 5-5
Pass the Parcel
• Problem: unwrap the layers of paper around a
parcel in order to reveal the present inside
• We can solve this iteratively:
While (there is paper) remove paper.
• Let's also solve this recursively:
1 Unwrap one piece of paper
2 If (we find the prize) stop
3 Otherwise, pass the parcel to someone else
• We solve part of the problems with step 1. This
leaves a smaller problem which is solved with step
3. The base case is step 2.
• Note: the 3 steps for recursion don't have to occur
in order
- 6. © 2004 Pearson Addison-Wesley. All rights reserved 5-6
Implementing Recursion in Java
• Remember, we have to think of a recursive
solution to the problem first!
• We use a method to solve part of the problem, i.e.
step 1.
• To solve the smaller problem, we call a new
instance of the same method with the left-over
problem: this is step 2, i.e. the recursion.
• We need to ensure that, at some point, we won't
call a new instance of the same method: this is
step 3, i.e. the base case.
• At this point, a typical question: how can a Java
method call itself? What does this mean?
- 7. © 2004 Pearson Addison-Wesley. All rights reserved 5-7
Methods Can Call Methods
• We know that methods can call other methods:
public static void main()
{
int age;
System.out.print("What's your age: ");
age= scan.nextInt();
}
• What would happen if a method called itself?
• Let's see...
- 8. © 2004 Pearson Addison-Wesley. All rights reserved 5-8
The Blah Method
int blah(int value)
{
int result;
result = value * blah(value -1);
return(result);
}
• If in main() we do x= blah(4); what happens?
blah() tries to calculate 4 * blah(3)
but then another blah() tries to calculate 3*blah(2)
• This thing is never going to stop! So it's pretty
useless.
• What if we make it stop when the value is 1?
blah(X) is X * blah(X-1)
but blah(1) is always exactly 1
- 9. © 2004 Pearson Addison-Wesley. All rights reserved 5-9
A Blah Method That Stops
int blah(int value)
{
int result;
if (value == 1)
result = 1;
else
result = value * blah(value-1);
return(result);
}
• This is known as a recursive method or a recursive
function: the operation depends on itself.
• For it to work properly, the function at some point
must not call itself. It must bottom out.
- 10. © 2004 Pearson Addison-Wesley. All rights reserved 5-10
The Factorial Function
• In maths, Fact(X) = X * all the numbers below it
• For example, Fact(7) = 7 * 6 * 5 * 4 * 3 * 2 * 1
• But note: Fact(7) = 7 * (6 * 5 * 4 * 3 * 2 * 1), so
Fact(7) = 7 * Fact(6)
• So, we can also define Fact(X) recursively:
Fact(X) = X * Fact(X-1), when X>1
Fact(1) = 1
• Hmm, that's exactly the blah() method we have
already written. Let's rename it factorial().
- 11. © 2004 Pearson Addison-Wesley. All rights reserved 5-11
The Factorial Function
int factorial(int value)
{
int result;
if (value==1)
result=1;
else
result= value * blah(value-1);
return(result);
}
Base case
The Recursion
Solve one part of the problem
- 12. © 2004 Pearson Addison-Wesley. All rights reserved 5-12
But, How Can a Method Call Itself?
• I mean, won't the second method trample over all
of the local variables and parameters in the first
method? How can there be two methods at the
same time?
• Because, when a method starts up, it gets its own
copies of the parameters and any local variables.
• So when factorial() with parameter 5 calls
factorial() with parameter 4, they each have
separate parameter variables.
- 13. © 2004 Pearson Addison-Wesley. All rights reserved 5-13
Why Do We Need Recursion?
• Well, most of the time we don't. However,
sometimes it is very hard to avoid it.
• Recursion is used when a problem is best solved
by doing some of the work, which leaves a smaller
problem that can be solved the same way.
• Here is a common real-world problem that needs
recursion:
- 14. © 2004 Pearson Addison-Wesley. All rights reserved 5-14
Find Files Algorithm: Incomplete
findFiles(Folder F, String suffix)
{
List L;
get list L of everything in F;
for each thing in list L
{
if (it is a file and ends in suffix)
print it out;
if (we have found another folder G)
what do we do here?
}
}
• What do we do on the red line? We could cut &
paste the algorithm inside more { ... }.
• But what if there are folders inside G? And what if
they have folders?
- 15. © 2004 Pearson Addison-Wesley. All rights reserved 5-15
Find Files Algorithm: Complete
findFiles(Folder F, String suffix)
{
List L;
get list L of everything in F;
for each thing in list L
{
if (it is a file and ends in suffix)
print it out;
if (we have found another folder G)
findFiles(G, suffix);
}
}
• When we find a sub-folder, we start a separate method
to deal with the files in that folder.
• And if the sub-folder has its own sub-folder, we do the
same.
• Eventually, we hit folders that only have files, and so
the recursion will bottom-out.
- 16. © 2004 Pearson Addison-Wesley. All rights reserved 5-16
Find Files as Java Code
• Read through the Java code from the lab
• Try it out with “H:SD1” as the folder, and “java”
as the suffix
• Use the debugger to stop after the name of each
thing in the list has been found
• As the recursion happens, the debugger will show
you each instance of the method on the left
- 17. © 2004 Pearson Addison-Wesley. All rights reserved 5-17
The Towers of Hanoi Game
• Move the tower of disks from the left column to the
right column.
• Move only 1 disk at a time. Cannot put a bigger
disk on a smaller disk.
• Hint: If we would move the tower consisting of the
light-blue disk upwards to the middle column, we
could move the green disk to the right column.
- 18. © 2004 Pearson Addison-Wesley. All rights reserved 5-18
Towers of Hanoi: Recursively
moveTower(int N, int startPosn,
int endPosn, int tempPosn)
{
// Move the N-1 tower from its start position
// to the temp position
moveTower(N-1, startPosn, tempPosn, endPosn);
// Move the N'th disk from start to end
moveOneDisk(startPosn, endPosn);
// And move the N-1 tower on top of N'th disk
moveTower(N-1, tempPosn, endPosn, startPosn);
}
• But, we have forgotten about the “bottom out”
condition!
• How can we rectify this?
- 19. © 2004 Pearson Addison-Wesley. All rights reserved 5-19
Towers of Hanoi as Java Code
• Read through the code from the lab.
- 20. © 2004 Pearson Addison-Wesley. All rights reserved 5-20
Recursion as a Problem Solver
• Recursion can be a very elegant way of solving a
problem.
• You need:
a part of the problem which can be solved
immediately
a way of expressing the solution of the rest of
the problem in terms of itself
• The idea is to do some work, but “pass the buck”
(i.e. most of the problem) on to someone else.
• Eventually, all of the problem can get solved.
- 21. © 2004 Pearson Addison-Wesley. All rights reserved 5-21
The Fibonnaci Series
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
• Each number is equal to the sum of the previous
two numbers, i.e.
Fib(X)= Fib(X-1) + Fib(X-2)
but we also need Fib(1)=1, Fib(2)=1 to bottom
out.
• So, Fib(5)= Fib(4)+Fib(3)
• Fib(5)= (Fib(3)+Fib(2)) + (Fib(2)+Fib(1))
• Fib(5)=((Fib(2)+Fib(1))+1) + (1 + 1)
• Fib(5)= ((1+1)+1) + (1+1) = 5
• Group Activity: Write a recursive Fibonacci()
method.
- 22. © 2004 Pearson Addison-Wesley. All rights reserved 5-22
Reversing a String
• Group Activity: Write a recursive method to
reverse a String.
• Hint: get the first letter of the String, and the rest
of the String.
• Hint: then reverse the rest of the string.
• Hint: then glue the reversed substring and the
letter together again.