main index contents 11 main index contents lecture 4 csn 331 – fall 2004 chapter 15 fibonacci...

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

Post on 22-Dec-2015

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

1 Main IndexMain Index ContentsContents1 Main IndexMain Index ContentsContents

Lecture 4Lecture 4CSN 331 – Fall 2004CSN 331 – Fall 2004

Chapter 15Chapter 15

Fibonacci (again) Fibonacci (again) Dynamic ProgrammingDynamic Programming

PermutationsPermutations

Eight QueensEight QueensBacktrackingBacktracking

SummarySummary

Chapter 3Chapter 3

TemplatesTemplates

Recursion BasicsRecursion Basics

Power FunctionPower FunctionRecursive DefnRecursive DefnRecursive FunctionRecursive Function

Towers of HanoiTowers of Hanoi

Fibonacci NumbersFibonacci Numbers

SummarySummary

Page 2: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

2 Main IndexMain Index ContentsContents2 Main IndexMain Index ContentsContents

Selection Sort AlgorithmSelection Sort AlgorithmInteger VersionInteger 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])

. . .

}

}

Page 3: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

3 Main IndexMain Index ContentsContents3 Main IndexMain Index ContentsContents

Selection Sort AlgorithmSelection Sort AlgorithmString VersionString 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])

. . .

}

}

Page 4: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

4 Main IndexMain Index ContentsContents

Template SyntaxTemplate 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, ...>

Page 5: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

5 Main IndexMain Index ContentsContents

Template Syntax ExampleTemplate Syntax Exampletemplate <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;

}

}

}

Page 6: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

6 Main IndexMain Index ContentsContents

Template Function InstantiationTemplate 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

Page 7: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

7 Main IndexMain Index ContentsContents

Recursive AlgorithmsRecursive AlgorithmsUse 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.

Page 8: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

8 Main IndexMain Index ContentsContents8 Main IndexMain Index ContentsContents

Recursive Definition of the Recursive Definition of the Power FunctionPower 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

1,*

0,11 nxx

nx nn

Page 9: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

9 Main IndexMain Index ContentsContents9 Main IndexMain Index ContentsContents

Implementing the Recursive Implementing the Recursive Power FunctionPower 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);

}

Page 10: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

10 Main IndexMain Index ContentsContents10 Main IndexMain Index ContentsContents

Solving the Tower of Hanoi Solving the Tower of Hanoi Puzzle using RecursionPuzzle using Recursion

N eed le A

. . . . . . . .

N eed le CN eed le B N eed le C

. . . . . . . .

N eed le BN eed le A

N e e dle A N e e dle B N e e dle C

1

N e e dle B N e e dle CN e e dle A

2

3

N e e dle A N e e dle B N e e dle CN e e dle A N e e dle B N e e dle C

Page 11: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

11 Main IndexMain Index ContentsContents11 Main IndexMain Index ContentsContents

Solving the Tower of Hanoi Solving the Tower of Hanoi Puzzle using RecursionPuzzle using Recursion

N eed le A N eed le B N eed le C N eed le A N eed le B N eed le C

56

N eed le A N eed le B N eed le C N eed le A N eed le B N eed le C

7

N e e dle A N e e dle B N e e dle C N e e dle A N e e dle B N e e dle C

4

Page 12: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

12 Main IndexMain Index ContentsContents

Towers of HanoiTowers of Hanoivoid 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’;

}

Page 13: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

13 Main IndexMain Index ContentsContents

Fibonacci NumbersFibonacci Numbers(Recursive solution)(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, ...}

Page 14: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

14 Main IndexMain Index ContentsContents

Recursive calls for fib(5)Recursive calls for fib(5)

fib (5 )

fib (4 ) fib (3 )

fib (3 ) fib (2 ) fib (2 ) fib (1 )

fib (2 ) fib (1 ) fib (1 ) fib (0 ) fib (1 ) fib (0 )

fib (1 ) fib (0 )

Page 15: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

15 Main IndexMain Index ContentsContents

Fibonacci with Fibonacci with dynamic programmingdynamic 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;

}

Page 16: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

16 Main IndexMain Index ContentsContents16 Main IndexMain Index ContentsContents

Affect of fib(5) Using Dynamic Affect of fib(5) Using Dynamic ProgrammingProgramming

fib (5 )

fib (4 ) fib (3 )

fib (3 ) fib (2 ) fib (2 ) fib (1 )

fib (2 ) fib (1 ) fib (1 ) fib (0 ) fib (1 ) fib (0 )

fib (1 ) fib (0 )

6

5

21

3

4

Page 17: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

17 Main IndexMain Index ContentsContents

Fibonacci Numbers using Fibonacci Numbers using IterationIteration

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;

}

Page 18: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

18 Main IndexMain Index ContentsContents

PermutationsPermutationsRecursive ApproachRecursive 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

Page 19: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

19 Main IndexMain Index ContentsContents

PermutationsPermutationsvoid 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)

}

}

}

Page 20: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

20 Main IndexMain Index ContentsContents

The 8-Queens ExampleThe 8-Queens Example

Page 21: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

21 Main IndexMain Index ContentsContents21 Main IndexMain Index ContentsContents

The 8-Queens Example (Cont…)The 8-Queens Example (Cont…)

A t (4 ,4 ) at t ack fro m (0 ,0 ) A t (5 ,4 ) at t ack fro m (2 ,1 ) A t (6 ,4 ) at t ack fro m (4 ,2 ) A t (7 ,4 ) s u cces s

0

1

2

3

4

5

6

7

0 1 2 3 4 5 6 7

Page 22: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

22 Main IndexMain Index ContentsContents

Eight QueensEight Queensbool 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?

}

Page 23: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

23 Main IndexMain Index ContentsContents

Eight QueensEight Queensbool 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}

Page 24: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

24 Main IndexMain Index ContentsContents24 Main IndexMain Index ContentsContents

Summary Slide 1Summary 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.

Page 25: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

25 Main IndexMain Index ContentsContents25 Main IndexMain Index ContentsContents

Summary Slide 2Summary 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.

Page 26: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

26 Main IndexMain Index ContentsContents26 Main IndexMain Index ContentsContents

Summary Slide 3Summary 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 leadsto an O(n) algorithm to find the nth Fibonacci number.

- recursive function that does not apply dynamic programming has exponential running time.

Page 27: Main Index Contents 11 Main Index Contents Lecture 4 CSN 331 – Fall 2004 Chapter 15 Fibonacci (again) Dynamic Programming Permutations Eight Queens BacktrackingSummary

27 Main IndexMain Index ContentsContents27 Main IndexMain Index ContentsContents

Summary Slide 4Summary 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)