Download presentation
Presentation is loading. Please wait.
1
Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary Chapter 3 Templates Recursion Basics Power Function Recursive Defn Recursive Function Towers of Hanoi Fibonacci Numbers Summary
2
Main Index Contents 22 Main Index Contents Selection Sort Algorithm Integer 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
Main Index Contents 33 Main Index Contents Selection Sort Algorithm String 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
Main Index Contents 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
5
Main Index Contents 5 Template Syntax Example template 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
Main Index Contents 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
Main Index Contents 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
Main Index Contents 88 Main Index Contents Recursive Definition of the Power Function A recursive definition of x n distinguishes between … n = 0 (starting point) where x n = x 0 = 1 and n 1 where x n can be calculated using the calculated value of x n-1
9
Main Index Contents 99 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
Main Index Contents 10 Main Index Contents Solving the Tower of Hanoi Puzzle using Recursion
11
Main Index Contents 11 Main Index Contents Solving the Tower of Hanoi Puzzle using Recursion
12
Main Index Contents 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
Main Index Contents 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
Main Index Contents 14 Recursive calls for fib(5)
15
Main Index Contents 15 Fibonacci with dynamic programming int fibDyn (int n vector & 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
Main Index Contents 16 Main Index Contents Affect of fib(5) Using Dynamic Programming
17
Main Index Contents 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
Main Index Contents 18 Permutations Recursive 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
Main Index Contents 19 Permutations void permute (vector 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
Main Index Contents 20 The 8-Queens Example
21
Main Index Contents 21 Main Index Contents The 8-Queens Example (Cont…)
22
Main Index Contents 22 Eight Queens bool placeQ (vector & 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
Main Index Contents 23 Eight Queens bool queens (vector & 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 & 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
Main Index Contents 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
Main Index Contents 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
Main Index Contents 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 n th Fibonacci number. - recursive function that does not apply dynamic programming has exponential running time.
27
Main Index Contents 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)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.