a trek through recursion. help commander data (our main method) solve his mystery? suggestion: draw...

Post on 16-Jan-2016

214 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

A Trek through Recursion

Help Commander Data (our main method) solve his mystery?Suggestion: Draw a diagram to help yourself

Data starts by asking CounselorTroi for help

Ask(Troi)

Ask(Troi)

The counselor says that her answer is “W”

combined with Geordi’s answer combined with “D”

So return “W” + ask(Geordi) + “D”

Ask(Geordi)

Geordi LaForge says that his answer is “A”

combined with Lt. Barclay’s answer combined with “E”

So return “A” + ask(Barclay) + “E”

Ask(Barclay)

Reginald Barclay says that his answer is “R”

combined with Dr. Crusher’s answer combined with “E”

So return “R” + ask(Crusher) + “E”

Ask (Crusher)

Dr. Crusher says that the her answer is “P”

combined with Captain Picard’s answer combined with “P”

So return “P” + ask(Picard) + “P”

Ask(Picard)

Back at the base the captain says with an air of finality that his answer is “S”

return(“S”)

Understanding Recursion

• Trace through Data’s call Ask(Troi) and figure out the resulting String.

• Understanding that this is pseudo code and not strict Java what do you think would be needed inside the ask method to make the method stop with Picard’s answer?

A recursive way to find fibonacci numbers

public static long fibonacci(long number) {

if ((number == 0) || (number == 1)) // base cases return number; else // recursion step return fibonacci(number - 1) + fibonacci(number - 2);

}

Write out the steps (tree diagram?) as you trace through fibonacci(7)?

Why does this method use long data type instead of int?

Three rules of recursionfrom Prof. Fran Trees Drew University

Approach every recursive problem as if it were a journey; if you follow these rules, you will complete the journey successfully.

RULE 1:Find out how to take just one step.RULE 2:Break each journey down into one step

plus a smaller journey.RULE 3:Know when to stop (base case)

Finally

“In order to understand recursion you must understand recursion.”

From Dan R. Ghica, Java Workshop: Recursion

Applications of Recursion

Fractalshttp://www.shodor.org/interactivate/activities/KochSnowflake/

Area of Polygon

To compute the area of a polygon with more than three corner points:

• chop off a triangle and determine the area of the triangle (take one step).

• compute the area of the remaining polygon (a smaller journey)

top related