19
Java Lecture Recursion 29 th feb 2005 [email protected]

java_lect_24.ppt

Embed Size (px)

Citation preview

  • Java Lecture

    Recursion29th feb [email protected]

    CFILT java

  • Recursionsolve(problem){If problem is simple Return the answerElse {Break the problem as p1,p2,p3 pnFor each problem P solve (P);}}

    CFILT java

  • PropertiesCalls the same function with smaller i/p.Divide and conquer strategy

    CFILT java

  • Example

    Little tricky

    CFILT java

  • Application of recursion

    ?

    CFILT java

  • Towers of HanoiLets try thisHanoi

    RulesInputOutputSolution for 1, 2, 3, 4, n

    CFILT java

  • Define the problemGraphical interface NOWhat is input ?-Number of discs! What is output?-Final state ? Y/N-Sequence of moves ? -How to represent ?

    CFILT java

  • Analogy with recursionSolution for 4 discsCan the solution for 4 be broken?Broken problem must be small.It should be same as the main problem.When to stop ?Solution for x discs is very simple. Solve it directly

    CFILT java

  • StepsProblem definition Input representationOutput representationAlgorithmImplementation

    CFILT java

  • DesignWe know Recursive conditionTerminating condition

    Lets try the algorithm for n

    CFILT java

  • Input/OutputName the function solve_hanoiInput ~ argument ~ (integer n)OutputAssume 3 towers three names.. 3 variables t1 ,t2, t3t1 = leftt2 = middlet3 = rightAre the t1, t2, t3 also arguments ?

    CFILT java

  • Skeleton code Solve_hanoi(integer n, towers t1, t2, t3){Do something.Do somethingsolve_hanoi(some small n, t1, t2, t3)Do something.Do something}

    CFILT java

  • Temination Solve_hanoi(integer n, towers t1, t2, t3){If (n == 1) then move the discn from t1 to t3Do somethingsolve_hanoi(some small n)Do something.Do something}

    CFILT java

  • SubdivsionStart(X)End(Y)Middle(Z)N-1discsNth disc

    CFILT java

  • Contd.Solve_hanoi(integer n, towers t1, t2, t3){1. Move the n-1 discs from t1 to t2 using t32. Now move only remaining disc from t1 to t33. Move the n-1 discs from t2 to t3 using t1}

    Which steps are recursive ?

    CFILT java

  • Formulate recursive call Solve_hanoi(integer n, towers t1, t2, t3) {If (n == 1) then move the discn from t1 to t3.ElseSolve_hanoi(n-1, t1, t3, t2).move the discn from t1 to t3.Solve_hanoi(n-1, t2, t1, t3).}

    CFILT java

  • Complete java functionPublic static void solve_hanoi(int n, String t1, t2, t3){if (n == 1) then System.out.println(move the disc+n+ from +t1+ to + t3);else{solve_hanoi(n-1, t1, t3, t2)System.out.println(move the disc+n+ from +t1+ to + t3); solve_hanoi(n-1, t2, t1, t3)}}

    CFILT java

  • ReferencePlay the game or see the solutions herehttp://www.mazeworks.com/hanoi/Recursion:http://www.cs.ucla.edu/~klinger/dorene/math4.htmHistory of the game : http://www.lawrencehallofscience.org/Java/Tower/towerhistory.html

    CFILT java

  • CFILT java