Download presentation
Presentation is loading. Please wait.
Published byBrenda Hamilton Modified over 7 years ago
1
CIS265/506 Cleveland State University – Prof. Victor Matos
Chapter 18 Recursion CIS265/506 Cleveland State University – Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition by Y. Daniel Liang
2
1. Motivation Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem? There are several ways to solve this problem. An intuitive solution is to search the files in the subdirectories recursively.
3
2. Motivation Try to solve the following word game. Reference:
4
2. Motivation Pick a word from the pool of available choices.
Collocate the selected word on a feasible position in the board. If the word cannot be placed, return it to the pool and remove any other word from the board. Do the same with the remaining available words. Reference:
5
3. Motivation – Solving Complex Problems
The Eight Queens puzzle consists on placing eight queens on a chessboard such that no two queens are on the same row, same column, or same diagonal, as shown in figure below. Your turn: Try placing n Queens on an n*n board
6
3. Motivation – Solving Complex Problems
8-Queens Strategy Try to collocate each queen in the next unchecked column, choosing the first available row. Mark the corresponding row, column, and diagonals as checked. If the current queen cannot be collocated in any unchecked cell, try to collocate the previous queen in another row. Do the same with the remaining queens, stop when all queens are placed or no more placement opportunities arise.
7
3. Using Recursion Recursion is one of the techniques used when applying the Divide-and- Conquer problem solving strategy. Two important aspects of Recursion It is a way of defining some problems (regardless of their implementation) It is a way of solving problems.
8
Example1 - Exponentiation
Problem Calculate the value of bn where n is an integer, and n≥0. Observation: bn = { 1 if n=0; b*bn-1 if n ˃ 0 Example: Compute the value of 24 = 2 * 23 = 2 * 22 = 2 * 21 = 2 * 20 = 1
9
Example2 - Computing Factorial
Notation n ! = n * (n-1)! factorial( n ) = n * factorial( n-1 ); Example: Compute the value of 4! factorial(4) = 4 * factorial( 3 ) = 4 * ( 3 * factorial(2) ) = 4 * ( 3 * (2 * factorial(1)) ) = 4 * ( 3 * ( 2 * (1 * factorial(0)))) = 4 * (3 * ( 2 * ( 1 * 1 ))) = 4 * (3 * ( 2 * 1)) = 4 * (3 * 2 ) = 4 * 6 = 24 9
10
Tracing Recursive Solution
Fact(4) = 4 x 6 = 24 Fact(4) = 4 x Fact(3) Fact(3) = 3 x 2 = 6 Fact(3) = 3 x Fact(2) Backtrack Recursive descend Fact(2) = 2 x Fact(1) Fact(2) = 2 x 1 = 2 Fact(1) = 1 x Fact(0) Fact(1) = 1 x 1 =1 Fact(0) = 1 ⟵ Base case 10
11
Computing Factorial private static int fact(int n) { if ( n == 0 )
return 1; else return n*fact(n-1); }
12
factorial(4) Stack Trace
13
Computing factorial of large numbers
private static BigInteger bigFactorial(BigInteger n) { BigInteger bigZero = new BigInteger("0"); BigInteger bigOne = new BigInteger("1"); if (n.compareTo(bigZero) == 0) return bigOne; else return n.multiply( bigFactorial(n.subtract(bigOne)) ); } Note: Try to compute (1000!) the result contains over 2500 digits!!! 13
14
Other Example – Recursive Summation
Recursive sum of first n numbers f(0) = 0; f(n) = n + f(n-1); Example: f (12) = Observe that f(12) = 12 + f(11), and f (11) = Which in turn can be computed as f(11) = 11 + f(10) Likewise, f(10) = 10 + f(9), and so on, until f(0) = 0 is discovered f(11) f(10)
15
Recursive Summation Recursively calculate the sum:
private static double sumPowerTwo(int n) { if ( n == 1 ) return 1.0/2; else return 1.0 / Math.pow(2, n) + sumPowerTwo( n-1 ); }
16
Fibonacci Numbers fib(0) = 1; fib(1) = 1;
Fibonacci series: indices: fib(0) = 1; fib(1) = 1; fib(index) = fib(index -1) + fib(index -2); index >=2 fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0) +fib(1) = 1 + fib(1) = = 2
17
Fibonacci Numbers private static int fib(int n) {
if ((n == 1) || (n == 0)) return 1; else return fib(n - 2) + fib(n - 1); }
18
Fibonnaci Numbers, cont.
19
Fibonnaci Numbers.
20
Fibonnaci Numbers. Fibonacci Spiral
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … Known as “The fingerprint of God” See an interesting video at (watch at your own risk!) Images from: mathacademy.com,
21
Fibonnaci Numbers and Golden Ratio
Perhaps the earliest known definition of the ‘Golden Ratio’ was provided by the Greek mathematician Euclid. Theta (𝜑) is defined as: The golden ratio is the limit of the ratios of successive terms of the Fibonacci sequence (or any Fibonacci-like sequence), as originally shown by the astronomer Johannes Kepler (1610) known for his laws of planetary motion. Images from:
22
Fibonnaci Numbers – Closed Formula
The French mathematician Abraham de Moivre (1667) discovered a expression to evaluate the n-th Fibonnaci number without computing its predecessors. Moivre’s book on “The Doctrine of Chances” was favored by gamblers of his era. He also worked on connecting trigonometry and complex numbers. Try double theta = (1 + Math.sqrt(5))/2; System.out.println (theta); for (int n = 1; n<12; n++) { double fib = (Math.pow(theta, n) - Math.pow(-theta, -n) ) / Math.sqrt(5); System.out.printf ( "\nfib(%d)= \t%f ", n, fib); } Images from:
23
A Historical Digression 1200 – Events
Capture of Constantinople Mongol Archer Warrior University of Paris A Historical Digression 1200 – Events The University of Paris receives its charter from Philip II of France (fought III Crusade with Richard I Lionheart) 1202 – Leonardo of Pisa publishes first work on Fibonacci numbers 1204—Fourth Crusade sacks Byzantine Constantinople, creating the Latin Empire. 1215—King John signs Magna Carta 1217–1221—Fifth Crusade captures Egyptian city of Damietta, ultimately Crusaders withdraw. 1221—Venice signs a trade treaty with the Mongol Empire. —Sixth Crusade under the excommunicated Frederick II retake Jerusalem 1237–1240—Mongol Empire conquers Russia. 1243–1250—Second Holy Roman Empire–Papacy War. 1244—Crusaders are defeated at the Battle of La Forbie. 1248–1254—Seventh Crusade recaptures Egyptian city of Damietta. 1261—Byzantines under Michael VIII retake Constantinople from the Crusaders and Venice. 1265-Dominican friar and theologian, Thomas Aquinas begins to write his Summa Theologiae. 1268—Fall of the Crusader State of Antioch to the Mamelukes. 1271—Edward I of England and Charles of Anjou arrive in Acre, starting the Ninth Crusade. Second Council of Lyon attempts to unite the Churches of the Eastern Roman Empire with the Church of Rome. 1289—Crusader State of Tripoli falls to the Mamelukes. 1291—The capture of Acre ended the Crusader Kingdom of Jerusalem (the final Christian landholding remaining from the Crusades). Reference:
24
Characteristics of Recursion
All recursive methods have the following characteristics: One or more base cases (the simplest case) are used to stop recursion (boundary conditions). Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. In general, to solve a problem using recursion, you break it into sub-problems. If a sub-problem resembles the original problem, you can apply the same approach to solve the sub-problem recursively. This sub-problem is almost the same as the original problem in nature with a smaller size.
25
Problem Solving Using Recursion
Let us consider a simple problem of printing a message for n times. You can break the problem into two subproblems: One is to print the message one time and the other is to print the message for n-1 times. The second problem is the same as the original problem with a smaller size. The base case for the problem is n==0. private static void printMsg(String msg, int times) { // printing a message a number of times if (times==0) return; System.out.println(times + " " + msg); printMsg(msg, times-1); }
26
Version1: Palindrome Examples: 100a001, MADAMIMADAM, abccba are palindromes. private static boolean isPalindrome ( String str ) { if (str.length() == 0 || str.length() == 1) return true; char first = str.charAt(0); char last = str.charAt(str.length() - 1); if (first != last) return false; else { str = str.substring(1, str.length() - 1); return isPalindrome( str ); }
27
Version2: Recursive Helper Methods
Examples: 100a001, MADAMIMADAM, abccba are palindromes. public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); } public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return isPalindrome(s, low + 1, high - 1);
28
Triangular Numbers Pythagoreans though there was a mystical message in the sequence 1, 3, 6, 10, 15, 21, 28, … those values were called triangular numbers because of their connection to the graphical construction of straight triangles. Current 1 2 3 4 5 6 7 … Sum of previous 10 15 21 Result 28
29
Triangular Numbers & Right Triangles
How many bricks are needed to build a right pyramid of height (or base) n ?
30
Triangular Numbers private static int triangular(int n) { if ( n == 1)
return 1; else return n + triangular(n-1); }
31
Recursive Selection Sort
Find the largest number in the list and swap it with the last number. Ignore the last number and sort the remaining smaller list recursively. 55 66 44 11 22 33 largest 55 33 44 11 22 66 Do the same here with this smaller list 22 33 44 11 55 66 Repeat . . .
32
Recursive Selection Sort
public class SelectionSort { /** Main method */ /** Recursive method for sorting the numbers public static void main(String[] args) { /** find/place minimum number in each iteration */ // Initialize the list static void recursiveSelectionSort(double[] list double[] myList = {5.0, 4.4, 1.9, 2.9, 3.4, 3.5}; int low, int high) { // Print the original list if (low < high ) { System.out.println("My list before sort is: "); int indexOfMin = 0; printList(myList); double min = list[low]; for(int i=low+1; i<high; i++ ) { // Sort the list if (list[i] < min) { recursiveSelectionSort(myList, 0, myList.length-1); min = list[i]; indexOfMin = i; // Print the sorted list System.out.println(); System.out.println("My list after sort is: "); list[indexOfMin] = list[low]; } list[low] = min; /** The method for printing numbers */ recursiveSelectionSort(list, low+1, high); static void printList(double[] list) { for (int i = 0; i < list.length; i++) }//recursiveSelectionSort System.out.print(list[i] + " "); }//class
33
Recursive Binary Search
Case 1: If the key is less than the middle element, recursively search the key in the first half of the array. Case 2: If the key is equal to the middle element, the search ends with a match. Case 3: If the key is greater than the middle element, recursively search the key in the second half of the array. 7 11 55 44 77 99 first middle last
34
Recursive Implementation
/** Use binary search to find the key in the list */ public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return recursiveBinarySearch(list, key, low, high); } // Use binary search to find the key in the list between list[low] & list[high] */ public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high);
35
Directory Size This section presents a problem that is difficult to solve without using recursion. The problem is to find the size of a directory. The size of a directory is the sum of the sizes of all files in the directory. A directory may contain subdirectories.
36
Directory Size public class DirectorySize { public static void main(String[] args) { System.out.print("Enter a file or a directory: "); java.util.Scanner input = new java.util.Scanner(System.in); String s = input.nextLine(); try { System.out.println( directorySize( new File(s) ) ); } catch (IOException ex) { System.out.println(ex.toString()); public static long directorySize(File file) throws java.io.FileNotFoundException{ if (!file.exists()) throw new java.io.FileNotFoundException(file + " not found"); if (file.isFile()) { return file.length(); else { File[] files = file.listFiles(); long size = 0; for (int i = 0; i < files.length; i++) size += directorySize(files[i]); return size;
37
Towers of Hanoi Invented by french mathematician Edouard Lucas (1842)
There are n disks labeled 1, 2, 3, . . ., n, and three towers labeled A, B, and C. No disk can be on top of a smaller disk at any time. All the disks are initially placed on tower A. Only one disk can be moved at a time, and it must be the top disk on the tower. Invented by french mathematician Edouard Lucas (1842) Image from Wikipedia 7/8/2011
38
A Historical Digression 1842 - Events
Commonwealth v. Hunt: the Massachusetts Supreme Court makes strikes and unions legal in the United States. Mexican troops led by Rafael Vasquez invade Texas, briefly occupy San Antonio, and then head back to the Rio Grande. Giuseppe Verdi's third opera Nabucco premieres in Milan; its success establishes Verdi as one of Italy's foremost opera writers. Anesthesia is used for the first time in an operation (Dr. Crawford Long performed the operation using ether). Dorr Rebellion: Militiamen supporting Thomas Wilson Dorr attack the arsenal in Providence, Rhode Island but are repulsed. The Tri-Kap fraternity is founded at Dartmouth College. It is the oldest local fraternity in the nation. The Armed Occupation Act is signed, providing for the armed occupation and settlement of the unsettled part of the Peninsula of East Florida. The Mines Act 1842 becomes law, prohibiting underground work for all women and boys under 10 years old in England. The Citadel, The Military College of South Carolina is established. The Income Tax Act 1842 is passed in the United Kingdom; 7 pence on the pound sterling, for incomes over 150 pounds. The first pils beer is brewed in the Czech city of Pilsen. The Pils is the original lager beer of which all modern lagers are copies. Founding of: Cumberland University Wesleyan University University of Notre Dame (by Father Edward Sorin, CSC of the Congregation of Holy Cross) Hollins University (in Roanoke, Virginia by Charles Cocke) Villanova University (in Villanova, Pennsylvania by the Augustinian order) Indiana University Bloomington Indiana University Maurer School of Law Willamette University in Salem, Oregon Taken from:
39
Towers of Hanoi, cont.
40
Solution to Towers of Hanoi
The Towers of Hanoi problem can be decomposed into three subproblems. 2 1 3 Step 2. Move disk n from A to B
41
Solution to Towers of Hanoi
Move the first n - 1 disks from A to C with the assistance of tower B. Move disk n from A to B. Move n - 1 disks from C to B with the assistance of tower A.
42
Solution to Towers of Hanoi
public static void main(String[] args) { int n = 4; // moving disks from A to B using C as auxiliary tower System.out.println("Towers of Hanoi. The moves are:"); moveDisks(n, 'A', 'B', 'C'); } private static void moveDisks( int n, char fromTower, char toTower, char auxTower) { if (n == 1) System.out.println("Move disk " + n + " from " + fromTower + " to " + toTower); else { moveDisks(n-1, fromTower, auxTower, toTower); moveDisks(n-1, auxTower, toTower, fromTower);
43
Greatest Common Divisor - GCD
gcd(2, 3) = 1 gcd(2, 10) = 2 gcd(25, 35) = 5 gcd(14, 28) = 14 Approach 1: Brute-force, start from min(n, m) down to 1, to check if a number is common divisor for both m and n, if so, it is the greatest common divisor. Approach 2: Euclid’s algorithm Approach 3: Recursive method GCD is the largest positive integer that divides The numbers without a remainder
44
Greatest Common Divisor - GCD
Example: Find GCD for 35, 25 Approach 1: Brute-force, start from min(n, m) down to 1, to check if a number is common divisor for both m and n, if so, it is the greatest common divisor. candidateSolution Is (35 % candidateSolution==0) && (25 % candidateSolution==0) ? 25 false 24 23 22 21 . . . 5 true min(35, 25) ⟶
45
Approach 2: Euclid’s algorithm
// Get absolute value of numb1 and numb2; n1 = Math.abs(numb1); n2 = Math.abs(numb2); // r is the remainder of n1 divided by n2; r = n1 % n2; while (r != 0) { n1 = n2; n2 = r; } // When r is 0, n2 is the greatest common // divisor between n1 and n2 return n2;
46
Approach 2: Euclid’s algorithm
Example: Find GCD for 35, 25 n1 n2 r = n1 % n2 35 25 10 5 GCD(35,25) is 5
47
Approach 3: Recursive Method
numb2 if ( numb1 % numb2 = 0 ); gcd(numb1, numb2) = gcd(numb2, numb1 % numb2) otherwise; private static int gcd(int numb1, int numb2) { if (numb1 % numb2 == 0) return numb2; else return gcd(numb2, numb1 % numb2 ); }
48
Historical Digression EUCLID
(300 BC) Also known as Euclid of Alexandria, was a Greek mathematician, often referred to as the "Father of Geometry". Little is known about Euclid's life. It is believed that Euclid may have studied at Plato's Academy in Athens. Taken from: Plato's academy, mosaic from Pompeii.
49
Knapsack Problem Load a knapsack with any number of items without exceeding its capacity. //knapsack problem. Simple case - no optimization ArrayList<Integer> items = new ArrayList<Integer> ( Arrays.asList(8, 2, 9, 4, 1, 5, 3, 4, 2, 6, 7)); ArrayList<Integer> solution = new ArrayList<Integer>(); knapsack(16, solution, items); for (int n : solution){ System.out.println("Knapsack: " + n ); } Picture taken from:
50
Knapsack Problem Load a knapsack with any number of items without exceeding its capacity. private static void knapsack(int maxWeight, ArrayList<Integer> solution, ArrayList<Integer> items) { if ((maxWeight >= 0 ) && (items.size()>0) ) { int item = items.remove(0); solution.add(0, item); knapsack(maxWeight-item, solution, items); } else { int item = solution.remove(0); if (items.size()==0) return; else{ knapsack(maxWeight+item, solution, items); Picture taken from:
51
Fractals? A fractal is a geometrical figure just like triangles, circles, and rectangles, but fractals can be divided into parts, each of which is a reduced-size copy of the whole.
52
Sierpiński Triangle It begins with an equilateral triangle, which is considered to be the Sierpinski fractal of order (or level) 0, as shown in Figure (a). Connect the midpoints of the sides of the triangle of order 0 to create a Sierpinski triangle of order 1, as shown in Figure (b). Leave the center triangle intact. Connect the midpoints of the sides of the three other triangles to create a Sierpinski of order 2, as shown in Figure (c). You can repeat the same process recursively to create a Sierpinski triangle of order 3, 4, ..., and so on, as shown in Figure (d).
53
Sierpinski Triangle Solution
54
Sierpinski Triangle Solution
public void drawTriangle (int order, Point p1, ponit p2, Point p3) if (order == 0) return; else { // calculate midpoints of triangle p1-p2-p3 p12 = midPoint (p1, p2); p13 = midPoint(p1, p3); p23 = midPoint(p2, p3); // draw inner Sierpinski triangles of smaller order drawTriangle(order-1, p1, p12, p13); drawTriangle(order-1, p12, p2, p23); drawTriangle(order-1, p13, p23, p3); }
55
Eight Queens
56
Eight Queens
57
Eight Queens // start by calling: search(0);
// search for a solution starting on specified row private static boolean search(int row){ if (row == SIZE) return true; for (int column=0; column < SIZE; column++){ queens[row] = column; //place a queen at row,column if (isValid(row, column) && search(row+1)){ System.out.println("Queen at: " + row + " : " + column); } return false; }//search // check if a queen can be placed at row i and column j private static boolean isValid(int row, int column){ for(int i=1; i<= row; i++){ if ( queens[row-i] == column //check column || queens[row-i] == column - i //check upleft diagonal || queens[row-i] == column + i )//check upright diagonal }//isValid
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.