SlideShare a Scribd company logo
1 of 22
Download to read offline
Week 11
Recursion
© 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.
© 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
© 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
© 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
© 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?
© 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...
© 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
© 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.
© 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().
© 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
© 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.
© 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:
© 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?
© 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.
© 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
© 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.
© 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?
© 2004 Pearson Addison-Wesley. All rights reserved 5-19
Towers of Hanoi as Java Code
• Read through the code from the lab.
© 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.
© 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.
© 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.

More Related Content

Similar to Week11

Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and RecursionTushar B Kute
 
(Radhika) presentation on chapter 2 ai
(Radhika) presentation on chapter 2 ai(Radhika) presentation on chapter 2 ai
(Radhika) presentation on chapter 2 aiRadhika Srinivasan
 
Recursion, debugging in c
Recursion, debugging in cRecursion, debugging in c
Recursion, debugging in cSaule Anay
 
Greedy Algorithms WITH Activity Selection Problem.ppt
Greedy Algorithms WITH Activity Selection Problem.pptGreedy Algorithms WITH Activity Selection Problem.ppt
Greedy Algorithms WITH Activity Selection Problem.pptRuchika Sinha
 
Course Design Best Practices
Course Design Best PracticesCourse Design Best Practices
Course Design Best PracticesKeitaro Matsuoka
 
problem solve and resolving in ai domain , probloms
problem solve and resolving in ai domain , problomsproblem solve and resolving in ai domain , probloms
problem solve and resolving in ai domain , problomsSlimAmiri
 
Simulated annealing-global optimization algorithm
Simulated annealing-global optimization algorithmSimulated annealing-global optimization algorithm
Simulated annealing-global optimization algorithmAkhil Prabhakar
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms NotesAndres Mendez-Vazquez
 
Roots of equations
Roots of equationsRoots of equations
Roots of equationsRobinson
 
Roots of equations
Roots of equationsRoots of equations
Roots of equationsRobinson
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prologbaran19901990
 

Similar to Week11 (20)

Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
 
Heapsort
HeapsortHeapsort
Heapsort
 
Heapsort
HeapsortHeapsort
Heapsort
 
(Radhika) presentation on chapter 2 ai
(Radhika) presentation on chapter 2 ai(Radhika) presentation on chapter 2 ai
(Radhika) presentation on chapter 2 ai
 
Recursion, debugging in c
Recursion, debugging in cRecursion, debugging in c
Recursion, debugging in c
 
Greedy Algorithms WITH Activity Selection Problem.ppt
Greedy Algorithms WITH Activity Selection Problem.pptGreedy Algorithms WITH Activity Selection Problem.ppt
Greedy Algorithms WITH Activity Selection Problem.ppt
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
 
Beginning Python
Beginning PythonBeginning Python
Beginning Python
 
12 deadlock concept
12 deadlock concept12 deadlock concept
12 deadlock concept
 
Course Design Best Practices
Course Design Best PracticesCourse Design Best Practices
Course Design Best Practices
 
problem solve and resolving in ai domain , probloms
problem solve and resolving in ai domain , problomsproblem solve and resolving in ai domain , probloms
problem solve and resolving in ai domain , probloms
 
Module 1 topic 1 notes
Module 1 topic 1 notesModule 1 topic 1 notes
Module 1 topic 1 notes
 
Simulated annealing-global optimization algorithm
Simulated annealing-global optimization algorithmSimulated annealing-global optimization algorithm
Simulated annealing-global optimization algorithm
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
 
Roots of equations
Roots of equationsRoots of equations
Roots of equations
 
Roots of equations
Roots of equationsRoots of equations
Roots of equations
 
Logic Programming and ILP
Logic Programming and ILPLogic Programming and ILP
Logic Programming and ILP
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 
october9.ppt
october9.pptoctober9.ppt
october9.ppt
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
 

More from hccit

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syllhccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guidehccit
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12hccit
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014hccit
 
Photoshop
PhotoshopPhotoshop
Photoshophccit
 
Flash
FlashFlash
Flashhccit
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs emailhccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overviewhccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochurehccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exerciseshccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questionshccit
 
Movies questions
Movies questionsMovies questions
Movies questionshccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questionshccit
 
Section b
Section bSection b
Section bhccit
 
Section a
Section aSection a
Section ahccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mjhccit
 

More from hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
 
Photoshop
PhotoshopPhotoshop
Photoshop
 
Flash
FlashFlash
Flash
 
University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
 
Movies questions
Movies questionsMovies questions
Movies questions
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
 
Section b
Section bSection b
Section b
 
B
BB
B
 
A
AA
A
 
Section a
Section aSection a
Section a
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
 

Recently uploaded

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

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.