1 / 27

Main Index

Lecture 4 CSN 331 – Fall 2004. 1. Main Index. Contents. Chapter 3 Templates Recursion Basics Power Function Recursive Defn Recursive Function Towers of Hanoi Fibonacci Numbers Summary. Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens Backtracking

janina
Download Presentation

Main Index

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 4 CSN 331 – Fall 2004 1 Main Index Contents • Chapter 3 • Templates • Recursion Basics • Power Function • Recursive Defn • Recursive Function • Towers of Hanoi • Fibonacci Numbers • Summary • Chapter 15 • Fibonacci (again) • Dynamic Programming • Permutations • Eight Queens • Backtracking • Summary

  2. 2 Main Index Contents Selection Sort AlgorithmInteger Version void selectionSort (int arr[], int n) { . . . int temp; // used for the exchange for (pass = 0; pass < n-1; pass++) { . . . // compare integer elements if (arr[j] < arr[smallIndex]) . . . } }

  3. 3 Main Index Contents Selection Sort AlgorithmString Version void selectionSort (string arr[], int n) { . . . string temp; //used for the exchange for (pass = 0; pass < n-1; pass++) { . . . // compare string elements if (arr[j] < arr[smallIndex]) . . . } }

  4. Template Syntax • template function syntax includes the keyword template followed by a non-empty list of formal types enclosed in angle brackets. • In the argument list, each type is preceded by the keyword typename, and types are separated by commas. // argument list with a multiple template // types template <typename T, typename U, typename V, ...>

  5. Template Syntax Example template <typename T> void selectionSort (T arr[], int n) { for (int pass = 0; pass < n-1; pass++) { // scan unsorted sublist to find smallest value int smallIndex = pass; for (int j = pass+1; j < n; j++) if (arr[j] < arr[smallIndex]) smallIndex = j; // swap smallest value with leftmost if (smallIndex != pass) { T temp = arr[pass]; arr[pass] = arr[smallIndex]; arr[smallIndex] = temp; } } }

  6. Template Function Instantiation • The compiler does not create the executable code for a template function until it encounters a call to it • The actual parameter type(s) in the call determine the template type T, and a version of the function is create for that actual type • int A[10]; • selectionSort( A, 10); // int array • String S[50]; • selectionSort( S, 50); // string array

  7. Recursive Algorithms • Use a recursive function to implement a recursive algorithm. The recursive function must consists of … 1. One or more stopping conditions (base cases) that can be directly evaluated for certain arguments. 2. One or more recursive steps in which a current value of the function can be computed by calling the function with arguments that will eventually arrive at a stopping condition.

  8. 8 Main Index Contents Recursive Definition of the Power Function • A recursive definition of xn distinguishes between … • n = 0 (starting point) where xn = x0 = 1 and • n  1 where xn can be calculated using the calculated value of xn-1

  9. 9 Main Index Contents Implementing the Recursive Power Function double power(double x, int n) // pre: n is non-negative { if (n == 0) // base case return 1.0; else // recursive step return x * power(x,n-1); }

  10. 10 Main Index Contents Solving the Tower of Hanoi Puzzle using Recursion

  11. 11 Main Index Contents Solving the Tower of Hanoi Puzzle using Recursion

  12. Towers of Hanoi void hanoi (int n, char src, char dest, char spare) { if (n > 1) { hanoi(n-1,src,spare,dest); cout << “move ” << src << “ to ” << dest << ‘\n’; hanoi(n-1,spare,dest,src); } else // last disk (n == 1) cout << “move ” << src << “ to ” << dest << ‘\n’; }

  13. Fibonacci Numbers(Recursive solution) int fib (int n) { if ((n == 0) || (n == 1)) // base cases return 1; else // general case // (sum of previous two values) return (fib(n-1) + fib(n-2)); } The sequence of Fibonacci numbers. {1, 1, 2, 3, 5, 8, 13, 21, 34, ...}

  14. Recursive calls for fib(5)

  15. Fibonacci with dynamic programming int fibDyn (int n vector<int>& fibList) { // pre: fibList contains all -1 values int fibValue; if(fibList[n] >= 0) // previously computed return fibList[n]; if (n <= 1) // base cases (0 & 1) fibValue = 1; else fibValue = fibDyn(n-1,fibList) + fibDyn(n-2,fibList); fibList[n] = fibValue; // save value in fibList return fibValue; }

  16. 16 Main Index Contents Affect of fib(5) Using Dynamic Programming

  17. Fibonacci Numbers using Iteration int fibiter (int n) { int oneback = 1, twoback = 1, current; if (n == 0 || n == 1) // base cases return 1; else // compute successive terms for (int i = 3; i <= n; i++) { current = oneback + twoback; twoback = oneback; oneback = current; } return current; }

  18. PermutationsRecursive Approach • Permutations of a list of n values include all possible re-orderings of those values • The number of permutations is n! • We will use a vector (permList) to hold the values • At each level of recursion (i), we create n-i recursive calls • Prior to each recursive call permList[i] is swapped with permList[j], for all i < j < n

  19. Permutations void permute (vector<int> permList, int index) { // permList must be value parameter int vSize = permList.size(); if (index == vsize-1) writeList(permList); // show result else { for (int i =index+1; i<vSize; i++) { int temp = permList[index]; permList[index] = perList[i]; permList[i] = temp; // shuffle positions index+1 .. vsize-1 permute(permList, index+1) } } }

  20. The 8-Queens Example

  21. 21 Main Index Contents The 8-Queens Example (Cont…)

  22. Eight Queens bool placeQ (vector<int>& qList, int col) { bool found = false; if (col == 8) found = true; // all 8 queens placed else { int row = 0; while (row < 8 && !found) // place queen in column { if (safeLoc(row,col,qlist)) { qList[col] = row; // place queen on row found = placeQ(qList,col+1); // place the rest? if (!found) row++; // try next row this column } else row++; // not safe, move queen to next row } } return found; // found complete solution? }

  23. Eight Queens bool queens (vector<int>& qList, int row) { qList[0] = row; // start at board[row,0] return placeQ(qList,1); // continue in column 1 } bool safeLoc (int row, int col, const vector<int>& qList) { for (int qCol = 0; qCol < col; qCol++) { int qRow = qList[qCol]; if ((qRow == row) || (qCol-qRow == col-row) || (qCol+qRow == col+row) ) return false; // on same row or diagonal } return true; // safe, not under attack }

  24. 24 Main Index Contents Summary Slide 1 §- C++ provides a template mechanism that allows a programmer to write a single version of a function with general type arguments. - If a main program wants to call the function several times with different runtime arguments, the compiler looks at the types of the runtime arguments and creates different versions of the function that matches the types.

  25. 25 Main Index Contents Summary Slide 2 §- An algorithm is recursive if it calls itself for smaller problems of its own type. §-Eventually, these problems must lead to one or more stopping conditions. - The solution at a stopping condition leads to the solution of previous problems. - In the implementation of recursion by a C++ function, the function calls itself.

  26. 26 Main Index Contents Summary Slide 3 §- Dynamic Programming (top down) 1) Fibonacci function - uses a vector to store Fibonacci numbers as a recursive function computes them - avoids redundant recursive calls and leads to an O(n) algorithm to find the nth Fibonacci number. - recursive function that does not apply dynamic programming has exponential running time.

  27. 27 Main Index Contents Summary Slide 4 §- Backtracking Algorithm (8 Queens) - find a consistent partial solution (place a queen safely in current column) - try to recursively extend the partial solution to a complete solution (place queen in next column …) - If recursive step fails to find a complete solution, it returns and the algorithm tries again from a new consistent partial solution. (replace queen in current column & continue, or return to previous column if necessary)

More Related