Recursion in Java

993 views

Published on

Recursion and Problem Solving in Java.

Topics:
Definition and divide-and-conquer strategies
Simple recursive algorithms
Fibonacci numbers
Dicothomic search
X-Expansion
Proposed exercises
Recursive vs Iterative strategies
More complex examples of recursive algorithms
Knight’s Tour
Proposed exercises


Teaching material for the course of "Tecniche di Programmazione" at Politecnico di Torino in year 2012/2013. More information: http://bit.ly/tecn-progr

Published in: Education, Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
993
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
44
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Recursion in Java

  1. 1. RecursionTecniche di Programmazione – A.A. 2012/2013
  2. 2. Summary1. Definition and divide-and-conquer strategies2. Simple recursive algorithms1. Fibonacci numbers2. Dicothomic search3. X-Expansion4. Proposed exercises3. Recursive vs Iterative strategies4. More complex examples of recursive algorithms1. Knight’sTour2. Proposed exercisesA.A. 2012/2013Tecniche di programmazione2
  3. 3. Definition and divide-and-conquerstrategiesRecursion
  4. 4. Definition A method (or a procedure or a function) is defined asrecursive when: Inside its definition, we have a call to the same method(procedure, function) Or, inside its definition, there is a call to another method that,directly or indirectly, calls the method itself An algorithm is said to be recursive when it is based onrecursive methods (procedures, functions)A.A. 2012/2013Tecniche di programmazione4
  5. 5. Example: Factorialpublic long recursiveFactorial(long N){long result = 1 ;if ( N == 0 )return 1 ;else {result = recursiveFactorial(N-1) ;result = N * result ;return result ;}}0!≝1∀N≥1:N!≝N× N−1 !A.A. 2012/2013Tecniche di programmazione5
  6. 6. Motivation Many problems lend themselves, naturally, to a recursivedescription: We define a method to solve sub-problems similar to the initialone, but smaller We define a method to combine the partial solutions into theoverall solution of the original problemDivide etimperaGaius Julius CaesarA.A. 2012/2013Tecniche di programmazione6
  7. 7. Divide et Impera – Divide and Conquer Solution = Solve ( Problem ) ; Solve ( Problem ) { List<SubProblem> subProblems = Divide ( Problem ) ; For ( each subP[i] in subProblems ) { SubSolution[i] = Solve ( subP[i] ) ; } Solution = Combine ( SubSolution[ ] ) ; return Solution ; }A.A. 2012/2013Tecniche di programmazione7
  8. 8. Divide et Impera – Divide and Conquer Solution = Solve ( Problem ) ; Solve ( Problem ) { List<SubProblem> subProblems = Divide ( Problem ) ; For ( each subP[i] in subProblems ) { SubSolution[i] = Solve ( subP[i] ) ; } Solution = Combine ( SubSolution[ ] ) ; return Solution ; }“a” sub-problems, each“b” times smaller thanthe initial problemrecursive callA.A. 2012/2013Tecniche di programmazione8
  9. 9. How to stop recursion? Recursion must not be infinite Any algorithm must always terminate! After a sufficient nesting level, sub-problems become sosmall (and so easy) to be solved: Trivially (ex: sets of just one element) Or, with methods different from recursionA.A. 2012/2013Tecniche di programmazione9
  10. 10. Warnings Always remember the “termination condition” Ensure that all sub-problems are strictly “smaller” thanthe initial problemA.A. 2012/2013Tecniche di programmazione10
  11. 11. Divide et Impera – Divide and Conquer Solve ( Problem ) { if( problem is trivial ) Solution = Solve_trivial ( Problem ) ; else { List<SubProblem> subProblems = Divide ( Problem ) ; For ( each subP[i] in subProblems ) { SubSolution[i] = Solve ( subP[i] ) ; } Solution = Combine ( SubSolution[ ] ) ; } return Solution ; }do recursionA.A. 2012/2013Tecniche di programmazione11
  12. 12. What about complexity?A.A. 2012/2013Tecniche di programmazione12 a = number of sub-problems for a problem b = how smaller sub-problems are than the original one n = size of the original problem T(n) = complexity of Solve …our unknown complexity function Θ(1) = complexity of Solve_trivial …otherwise it wouldn’t be trivial D(n) = complexity of Divide C(n) = complexity of Combine
  13. 13. Divide et Impera – Divide and Conquer Solve ( Problem ) { if( problem is trivial ) Solution = Solve_trivial ( Problem ) ; else { List<SubProblem> subProblems = Divide ( Problem ) ; For ( each subP[i] in subProblems ) { SubSolution[i] = Solve ( subP[i] ) ; } Solution = Combine ( SubSolution[ ] ) ; } return Solution ; }T(n)Θ(1)D(n)C(n)T(n/b)a timesA.A. 2012/2013Tecniche di programmazione13
  14. 14. Complexity computation T(n) = (1) for n  c D(n) + a T(n/b) + C(n) for n > c Recurrence Equation not easy to solve in the general case Special case: If D(n)+C(n)=(n) We obtain T(n) = (n log n).A.A. 2012/2013Tecniche di programmazione14
  15. 15. Simple recursive algorithmsRecursion
  16. 16. Fibonacci Numbers Problem: Compute the N-th Fibonacci Number Definition: FIBN+1 = FIBN + FIBN-1 for N>0 FIB1 = 1 FIB0 = 0A.A. 2012/2013Tecniche di programmazione16
  17. 17. Recursive solutionpublic long recursiveFibonacci(long N) {if(N==0)return 0 ;if(N==1)return 1 ;long left = recursiveFibonacci(N-1) ;long right = recursiveFibonacci(N-2) ;return left + right ;}Fib(0) = 0Fib(1) = 1Fib(2) = 1Fib(3) = 2Fib(4) = 3Fib(5) = 5A.A. 2012/2013Tecniche di programmazione17
  18. 18. AnalysisFIB(5)FIB(4)FIB(3)A.A. 2012/2013Tecniche di programmazione18
  19. 19. AnalysisFIB(5)FIB(4)FIB(3)FIB(1) FIB(2)FIB(0) FIB(1)A.A. 2012/2013Tecniche di programmazione19
  20. 20. AnalysisFIB(5)FIB(4)FIB(3)FIB(1) FIB(2)FIB(0) FIB(1)FIB(3) FIB(2)FIB(1) FIB(2)FIB(0) FIB(1) FIB(0)FIB(1)A.A. 2012/2013Tecniche di programmazione20
  21. 21. AnalysisFIB(5)FIB(4)FIB(3)FIB(1) FIB(2)FIB(0) FIB(1)FIB(3) FIB(2)FIB(1) FIB(2)FIB(0) FIB(1) FIB(0)FIB(1)A.A. 2012/2013Tecniche di programmazione21Complexity?
  22. 22. Example: dichotomic search Problem Determine whether an element x is present inside an orderedvector v[N] Approach Divide the vector in two halves Compare the middle element with x Reapply the problem over one of the two halves (left or right,depending on the comparison result) The other half may be ignored, since the vector is orderedA.A. 2012/2013Tecniche di programmazione22
  23. 23. Example1 3 4 6 8 9 11 12v 4xA.A. 2012/2013Tecniche di programmazione23
  24. 24. Example1 3 4 6 8 9 11 12v 4xyy<xyxA.A. 2012/2013Tecniche di programmazione24
  25. 25. Example1 3 4 6 8 9 11 12v 4x1 3 4 6 8 9 11 121 3 4 64 6yy<xyxA.A. 2012/2013Tecniche di programmazione25
  26. 26. Solutionpublic int find(int[] v, int a, int b, int x){if(b-a == 0) { // trivial caseif(v[a]==x) return a ; // foundelse return –1 ; // not found}int c = (a+b) / 2 ; // splitting pointif(v[c] >= x)return find(v, a, c, x) ;else return find(v, c+1, b, x) ;}A.A. 2012/2013Tecniche di programmazione26
  27. 27. Solutionpublic int find(int[] v, int a, int b, int x){if(b-a == 0) { // trivial caseif(v[a]==x) return a ; // foundelse return –1 ; // not found}int c = (a+b) / 2 ; // splitting pointif(v[c] >= x)return find(v, a, c, x) ;else return find(v, c+1, b, x) ;}Beware of integer-arithmeticapproximations!A.A. 2012/2013Tecniche di programmazione27
  28. 28. Quick referenceA.A. 2012/2013Tecniche di programmazione28
  29. 29. Exercise: Value X When working with Boolean functions, we often use thesymbol X, meaning that a given variable may haveindifferently the value 0 or 1. Example: in the OR function, the result is 1 when theinputs are 01, 10 or 11. More compactly, if the inputs areX1 or 1X.A.A. 2012/2013Tecniche di programmazione29
  30. 30. X-Expansion We want to devise an algorithm that, given a binary stringthat includes characters 0, 1 and X, will compute all thepossible combinations implied by the given string. Example: given the string 01X0X, algorithm must computethe following combinations 01000 01001 01100 01101A.A. 2012/2013Tecniche di programmazione30
  31. 31. Solution We may devise a recursive algorithm that explores thecomplete ‘tree’ of possible compatible combinations: Transforming each X into a 0, and then into a 1 For each transformation, we recursively seek other X in thestring The number of final combinations (leaves of the tree) isequal to 2N, if N is the number of X. The tree height is N+1.A.A. 2012/2013Tecniche di programmazione31
  32. 32. Combinations tree01X0X0100X 0110X01000 01001 01100 01101A.A. 2012/2013Tecniche di programmazione32
  33. 33. Exercise Compute the Binomial Coefficient (n m) exploiting therecurrence relations (derived fromTartaglia’s triangle): nmnnnnmnmnmn0,010111A.A. 2012/2013Tecniche di programmazione33
  34. 34. Exercise Compute the determinant of a square matrix Remind that: det( M 1x1 ) = m1,1 det( M NxN ) = sum of the products of all elements of a row(or column), times the determinants of the (N-1)x(N-1) sub-matrices obtained by deleting the row and column containingthe multiplying element, with alternating signs (-1)(i+j).Lapace’s Formula, athttp://en.wikipedia.org/wiki/DeterminantA.A. 2012/2013Tecniche di programmazione34
  35. 35. Recursive vs Iterative strategiesRecursion
  36. 36. Recursion and iteration Every recursive program can always be implemented inan iterative manner The best solution, in terms of efficiency and code clarity,depends on the problemA.A. 2012/2013Tecniche di programmazione36
  37. 37. Example: Factorial (iterative)public long iterativeFactorial(long N){long result = 1 ;for (long i=2; i<=N; i++)result = result * i ;return result ;}0!≝1∀N≥1:N!≝N× N−1 !A.A. 2012/2013Tecniche di programmazione37
  38. 38. Fibonacci (iterative)public long iterativeFibonacci(long N) {if(N==0) return 0 ;if(N==1) return 1 ;// now we know that N >= 2long i = 2 ;long fib1 = 1 ; // fib(N-1)long fib2 = 0 ; // fib(N-1)while( i<=N ) {long fib = fib1 + fib2 ;fib2 = fib1 ;fib1 = fib ;i++ ;}return fib1 ;}A.A. 2012/2013Tecniche di programmazione38
  39. 39. Dichotomic search (iterative)A.A. 2012/2013Tecniche di programmazione39public int findIterative(int[] v, int x) {int a = 0 ;int b = v.length-1 ;while( a != b ) {int c = (a + b) / 2; // middle pointif (v[c] >= x) {// v[c] is too large -> search leftb = c ;} else {// v[c] is too small -> search righta = c+1 ;}}if (v[a] == x)return a;elsereturn -1;}
  40. 40. Exercises Create an iterative version for the computation of thebinomial coefficient (n m). Analyze a possible iterative version for computing thedeterminant of a matrix. What are the difficulties? Can you find a simple iterative solution for the X-Expansion problem?A.A. 2012/2013Tecniche di programmazione40
  41. 41. More complex examples of recursivealgorithmsRecursion
  42. 42. Knight’s tour Consider a NxN chessboard, with the Knight movingaccording to Chess rules The Knight may move in 8 different cells We want to find a sequence of moves for the Knightwhere All cells in the chessboardare visited Each cell is touched exactly once The starting point is arbitraryA.A. 2012/2013Tecniche di programmazione42
  43. 43. Analysis Assume N=41A.A. 2012/2013Tecniche di programmazione43
  44. 44. Move 112,0,0Level of the next moveto tryCoordinates of the lastmoveA.A. 2012/2013Tecniche di programmazione44
  45. 45. Move 2212,0,03,2,1A.A. 2012/2013Tecniche di programmazione45
  46. 46. Move 33212,0,03,2,14,3,3A.A. 2012/2013Tecniche di programmazione46
  47. 47. Move 432412,0,03,2,14,3,35,1,2A.A. 2012/2013Tecniche di programmazione47
  48. 48. Move 535 2412,0,03,2,14,3,35,1,26,2,0A.A. 2012/2013Tecniche di programmazione48
  49. 49. Move 66 35 2412,0,03,2,14,3,35,1,26,2,07,3,2A.A. 2012/2013Tecniche di programmazione49
  50. 50. Move 76 35 24 712,0,03,2,14,3,35,1,26,2,07,3,28,1,3A.A. 2012/2013Tecniche di programmazione50
  51. 51. Move 86 35 24 71 82,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,1A.A. 2012/2013Tecniche di programmazione51
  52. 52. Move 96 35 2 94 71 82,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,2A.A. 2012/2013Tecniche di programmazione52
  53. 53. Move 106 35 2 94 71 82,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,2A.A. 2012/2013Tecniche di programmazione53
  54. 54. Move 116 35 2 94 71 8 102,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,3A.A. 2012/2013Tecniche di programmazione54
  55. 55. Move 126 35 2 911 4 71 8 102,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,1A.A. 2012/2013Tecniche di programmazione55
  56. 56. Move 1312 6 35 2 911 4 71 8 102,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,3,0 A.A. 2012/2013Tecniche di programmazione56
  57. 57. Move 146 35 2 9 1211 4 71 8 102,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,3,0 13,2,3A.A. 2012/2013Tecniche di programmazione57
  58. 58. Move 1513 6 35 2 9 1211 4 71 8 102,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,3,0 13,2,314,3,1A.A. 2012/2013Tecniche di programmazione58
  59. 59. Move 1613 6 35 2 9 1214 11 4 71 8 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,0A.A. 2012/2013Tecniche di programmazione59
  60. 60. Move 1713 6 35 2 9 1214 11 4 71 8 15 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,2A.A. 2012/2013Tecniche di programmazione60
  61. 61. Move 1813 6 35 2 9 1214 11 4 71 8 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,2A.A. 2012/2013Tecniche di programmazione61
  62. 62. Move 1913 6 35 2 9 1211 4 71 8 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,2A.A. 2012/2013Tecniche di programmazione62
  63. 63. Move 206 35 2 9 1211 4 71 8 13 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,1A.A. 2012/2013Tecniche di programmazione63
  64. 64. Move 216 35 2 9 1214 11 4 71 8 13 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,0A.A. 2012/2013Tecniche di programmazione64
  65. 65. Move 2215 6 35 2 9 1214 11 4 71 8 13 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,1A.A. 2012/2013Tecniche di programmazione65
  66. 66. Move 236 35 2 9 1214 11 4 71 8 13 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,1A.A. 2012/2013Tecniche di programmazione66
  67. 67. Move 246 35 2 9 1211 4 71 8 13 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,1A.A. 2012/2013Tecniche di programmazione67
  68. 68. Move 256 35 2 9 1211 4 71 8 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,1A.A. 2012/2013Tecniche di programmazione68
  69. 69. Move 266 35 2 911 4 71 8 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,1A.A. 2012/2013Tecniche di programmazione69
  70. 70. Move 276 35 2 94 71 8 1013,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,1A.A. 2012/2013Tecniche di programmazione70
  71. 71. Move 286 35 2 910 4 71 813,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,0A.A. 2012/2013Tecniche di programmazione71
  72. 72. Move 2911 6 35 2 910 4 71 813,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,1A.A. 2012/2013Tecniche di programmazione72
  73. 73. Move 3011 6 35 2 9 1210 4 71 813,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,3A.A. 2012/2013Tecniche di programmazione73
  74. 74. Move 3111 6 35 2 9 1210 4 71 8 1313,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,314,0,2A.A. 2012/2013Tecniche di programmazione74
  75. 75. Move 3211 6 35 2 9 1210 13 4 71 813,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,314,0,2 14,1,1A.A. 2012/2013Tecniche di programmazione75
  76. 76. Move 3311 6 35 2 9 1210 13 4 71 8 1413,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,314,0,2 14,1,115,0,3A.A. 2012/2013Tecniche di programmazione76
  77. 77. Move 3414 11 6 35 2 9 1210 13 4 71 813,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,314,0,2 14,1,115,0,3 15,3,0A.A. 2012/2013Tecniche di programmazione77
  78. 78. Move 3511 6 35 2 9 1210 13 4 71 813,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,314,0,2 14,1,115,0,3 15,3,0A.A. 2012/2013Tecniche di programmazione78
  79. 79. Move 3611 6 35 2 9 1210 4 71 813,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,314,0,2 14,1,115,0,3 15,3,0A.A. 2012/2013Tecniche di programmazione79
  80. 80. Move 3711 6 35 2 910 4 71 813,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,314,0,2 14,1,115,0,3 15,3,0A.A. 2012/2013Tecniche di programmazione80
  81. 81. Move 386 35 2 910 4 71 8 1113,3,02,0,03,2,14,3,35,1,26,2,07,3,28,1,39,0,110,2,211,0,312,1,113,2,314,3,115,1,016,0,214,3,115,1,016,3,111,1,012,3,113,2,314,0,2 14,1,115,0,3 15,3,012,0,2A.A. 2012/2013Tecniche di programmazione81
  82. 82. ComplexityA.A. 2012/2013Tecniche di programmazione82 The number of possible moves, at each step, is at most 8. The number of steps is N2. The solution tree has a number of nodes 8N^2. In the worst case The solution is in the right-most leave of the solution tree The tree is complete The number of recursive calls, in the worst case, istherefore (8N^2).
  83. 83. ImplementationA.A. 2012/2013Tecniche di programmazione83
  84. 84. The N Queens Consider a NxN chessboard, and N Queens that may actaccording to the chess rules Find a position for the N queens, such that no Queen isable to attach any other QueenA.A. 2012/2013Tecniche di programmazione84??
  85. 85. Domino gameA.A. 2012/2013Tecniche di programmazione85 Consider the game of Domino, composed of two-sidedpieces: each side is labeled with a number from 0 to 6.Allcombinations of number pairs are represented exactlyonce. Find the longest possible sequence of pieces, such thatconsecutive pieces have the same value on the adjacentsides.
  86. 86. ResourcesA.A. 2012/2013Tecniche di programmazione86 Algorithms in a Nutshell, By GeorgeT. Heineman, GaryPollice, Stanley Selkow, OReilly Media
  87. 87. Licenza d’usoA.A. 2012/2013Tecniche di programmazione87 Queste diapositive sono distribuite con licenza Creative Commons“Attribuzione - Non commerciale - Condividi allo stesso modo (CCBY-NC-SA)” Sei libero: di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico,rappresentare, eseguire e recitare questopera di modificare questopera Alle seguenti condizioni: Attribuzione — Devi attribuire la paternità dellopera agli autorioriginali e in modo tale da non suggerire che essi avallino te o il modo incui tu usi lopera. Non commerciale — Non puoi usare questopera per finicommerciali. Condividi allo stesso modo — Se alteri o trasformi questopera, o sela usi per crearne unaltra, puoi distribuire lopera risultante solo con unalicenza identica o equivalente a questa. http://creativecommons.org/licenses/by-nc-sa/3.0/

×