More Recursion: Permutations and Towers of Hanoi COP 3502.

Slides:



Advertisements
Similar presentations
Tower of Hanoi Tower of Hanoi is a mathematical puzzle invented by a French Mathematician Edouard Lucas in The game starts by having few discs stacked.
Advertisements

The Towers of Hanoi or Apocalypse When?.
CS1010: Programming Methodology
More Recursion: Permutations and Towers of Hanoi
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Factorial Recursion stack Binary Search Towers of Hanoi
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
Recursion CSC 220: Data Structure Winter Introduction A programming technique in which a function calls itself. One of the most effective techniques.
Recursion. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Review of Recursion. Definition: Recursion - The process of a function calling itself.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Analysis of Algorithm Lecture 3 Recurrence, control structure and few examples (Part 1) Huma Ayub (Assistant Professor) Department of Software Engineering.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Recursion, Complexity, and Sorting By Andrew Zeng.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Recursion Jordi Cortadella Department of Computer Science.
# 1# 1 VBA Recursion What is the “base case”? What is the programming stack? CS 105 Spring 2010.
Chapter 8 Recursion Modified.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Recursion Review: A recursive function calls itself, but with a smaller problem – at least one of the parameters must decrease. The function uses the results.
By: Lokman Chan Recursive Algorithm Recursion Definition: A function that is define in terms of itself. Goal: Reduce the solution to.
Upon completion, the world will end…
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
CompSci Review of Recursion with Big-Oh  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
UNIT 17 Recursion: Towers of Hanoi.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Tower of Hanoi Tower of Hanoi is a mathematical puzzle invented by a French Mathematician Edouard Lucas in The game starts by having few discs stacked.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion.
COMP 51 Week Fourteen Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Abdulmotaleb El Saddik University of Ottawa
Lesson #6 Modular Programming and Functions.
Recursion Chapter 12.
Lesson #6 Modular Programming and Functions.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Java Software Structures: John Lewis & Joseph Chase
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Lesson #6 Modular Programming and Functions.
Jordi Cortadella Department of Computer Science
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
ECE 103 Engineering Programming
When Will The World End “Temple of Brahma” legend from the Indian city of Benares Priests must move 64 gold disks from one end of the temple to the other.
The Hanoi Tower Problem
Lesson #6 Modular Programming and Functions.
Recursive Thinking.
Presentation transcript:

More Recursion: Permutations and Towers of Hanoi COP 3502

Towers of Hanoi COP 3502

Recursion – Towers of Hanoi The Towers of Hanoi Is a mathematical puzzle that has a classic recursive solution that we are going to examine. The puzzle was invented by the French mathematician Edouard Lucas, based upon a legend: In an Indian temple there contains three posts surrounded by 64 golden disks. The monks have been moving the disks according to the puzzle rules since the beginning of time. And according to the legend, when the last move of the puzzle is completed, the world will end.

Recursion – Towers of Hanoi The Towers of Hanoi The goal is to move all disks from Tower#1 to Tower#3. The rules are: You can only move ONE disk at a time And you can NEVER put a bigger disk on top of a smaller disk.

Recursion – Towers of Hanoi The Towers of Hanoi Coming up with a Recursive Solution: Clearly an tower with more than 1 disk must be moved in pieces. We know that the bottom disk needs to moved to the destination tower. – In order to do that we need to move all disks above the bottom disk to the intermediate tower. – This leads to our recursive solution!

Recursion – Towers of Hanoi The Towers of Hanoi Solution: Regardless of the number of disks, we know we have to do the following steps: – The bottom disk needs to be moved to the destination tower 1)So step 1 must be to move all disks above the bottom disk to the intermediate tower. 2)In step 2, the bottom disk can now be moved to the destination tower. 3)In step 3, the disks that were initially above the bottom disk must now be put back on top of the destination tower.

Recursion – Towers of Hanoi The Towers of Hanoi Lets look at the problem with only 3 disks. Solution: Step 1: – Move top 2 disks to temp » we would have to solve this recursively, since we can only move 2 disks at a time. » Were going to assume that we know how to do the 2 disk problem (since this is solved recursively), and continue to the next step. Start Temp Finish

Recursion – Towers of Hanoi The Towers of Hanoi Lets look at the problem with only 3 disks. Solution: Step 2: – Move the last single disk from start to finish – Moving a single disk does not use recursion, and does not use the temp tower. – (In our program, a single disk move is represented with a print statement.) Start Temp Finish

Recursion – Towers of Hanoi The Towers of Hanoi Lets look at the problem with only 3 disks. Solution: Step 3: – Last step – Move the 2 disks from Temp to Finish » This would be done recursively. Start Temp Finish

Recursion – Towers of Hanoi Number of Steps: 3 disks required 7 steps 4 disks would requre 15 steps We get n disks would require 2 n - 1 steps HUGE number

Start Temp Finish

void doHanoi(int n, char start, char finish, char temp) { if (n==1) { printf(Move Disk from %c to %c\n, start, finish); } else { doHanoi(n-1, start, temp, finish); printf(Move Disk from %c to %c\n, start finish); doHanoi(n-1, temp, finish, start); } Start Temp Finish Rec call to get here: Single move, just print.

// Function Prototype void doHanoi(int n, char start, char finish, char temp); void main() { int disk; int moves; printf(Enter the # of disks you want to play with:); scanf(%d, &disk); // Print out the # of moves required moves = pow(2, disk)-1; printf(\nThe # of moves required is = %d \n, moves); // Show the moves using doHanoi doHanoi(disk, A, C, B); }

Permutations The permutation problem is as follows: Given a list of items, list all the possible orderings of those items. For example, here are all the permutations of CAT: CAT CTA ACT ATC TAC TCA

Permutations There are several different permutation algorithms, but since were focusing on recursion in this course, a recursive algorithm will be presented. (Feel free to come up with or research an iterative algorithm on your own)

Recursive Permutation Algorithm The idea is as follows: In order to list all the permutations of CAT, we can split our work into three groups of permutations: 1)Permutations that start with C. 2)Permutations that start with A. 3)Permutations that start with T. The recursion comes in here: When we list all permutations that start with C, they are nothing but strings formed by attaching C to the front of ALL permutations of AT. This is nothing but another permutation problem!!!

Recursive Permutation Algorith Number of recursive calls Often when recursion is taught, a rule of thumb is: recursive functions dont have loops Unfortunately, this rule of thumb is not always true! An exception to this rule is the permutation algorithm.

Recursive Permutation Algorith Number of recursive calls The problem is the number of recursive calls is variable. In the CAT example 3 recursive calls were needed BUT, what if we were permuting the letters in the word, COMPUTER? Then 8 recursive calls (1 for each possible starting letter) would be needed.

Recursive Permutation Algorith Number of recursive calls In other words… We need a loop in the algorithm for (each possible starting letter) – list all permutations that start with that letter What is the terminating condition? Permuting either 0 or 1 element. – In these cases theres nothing to permute In our code, we will use 0 as our terminating condition.

Recursive Permutation Algorithm The Permutation algorithm: As we have seen in previous examples some recursive functions take in an extra parameter compared to their iterative implementation This is usually used to keep track of the number of iterations left until the base case. This is the case for our permutation algorithm Shown in the following function…

Recursive Permutation Algorithm So k refers to the first k characters that are fixed in their original positions. // Pre-condition: str is a valid C String, and k //is non-negative and <= the // length of str. // Post-conditions: All of the permutations of str with //the first k characters fixed in //their original positions are //printed. Namely, if n is the lenth //of str, then (n-k)! permutations are //printed. void RecursivePermute(char str[], int k);

Recursive Permutation Algorithm So we terminate when k is equal to the length of the string, str This means: If k is equal to the length of the actual string, and all k values are fixed, theres nothing left to permute So we just print out that permutation // Pre-condition: str is a valid C String, and k //is non-negative and <= the // length of str. // Post-conditions: All of the permutations of str with //the first k characters fixed in //their original positions are //printed. Namely, if n is the lenth //of str, then (n-k)! permutations are //printed. void RecursivePermute(char str[], int k);

Recursive Permutation Algorithm If we do NOT terminate: We want a loop that tries each character at index k. // Pre-condition: str is a valid C String, and k //is non-negative and <= the // length of str. // Post-conditions: All of the permutations of str with //the first k characters fixed in //their original positions are //printed. Namely, if n is the lenth //of str, then (n-k)! permutations are //printed. void RecursivePermute(char str[], int k);

Recursive Permutation Algorithm The recursive algorithm: void RecursivePermute(char str[], int k) { int j; // Base-case: All fixed, so Print! if (k == strlen(Str)) pringf(%s\n, str); else { // Try each letter in spot j for (j=k; j<strlen(Str); j++) { // Place next letter in spot k. ExchangeCharacters(str, k, j); // Pring all with spot k fixed. RecursivePermute(str, k+1); // Put the old char back. ExchangeCharacters(str, j, k); }

Recursive Permutation Algorithm The main loop within the recursive algorithm: How do we get the different characters in the first position? (The C, A, T, in our CAT example) for (j=k; j<strlen(Str); j++) { ExchangeCharacters(str, k, j); RecursivePermute(str, k+1); ExchangeCharacters(str, j, k); }

Recursive Permutation Algorithm The main loop within the recursive algorithm: The ExchangeCharacters function: Takes in str, and swaps 2 characters within that string (at index k and index j) for (j=k; j<strlen(Str); j++) { ExchangeCharacters(str, k, j); RecursivePermute(str, k+1); ExchangeCharacters(str, j, k); }

Recursive Permutation Algorithm This function will swap the characters for us, Letting each character have a turn at being the 1 st character in the sub-string // Pre-condition: str is a valid C String and i,j are valid indices to that string. // Post-condition: The characters at i and j, will be swapped in str. void ExchangeCharacters(char str[], int i, int j) { char temp = str[i]; str[i] = str[j]; str[j] = temp; }

Recursive Permutation Algorithm The main loop within the recursive algorithm: So after we swap positions, we swap back so we can continue looping through the rest of the possible characters at position k. for (j=k; j<strlen(Str); j++) { ExchangeCharacters(str, k, j); RecursivePermute(str, k+1); ExchangeCharacters(str, j, k); }

Recursive Permutation Algorithm Recursive Permutation code in detail: 2 parameters to the function 1)The string we want to permute (for example CAT 2)And the integer k Represents the first k characters that are FIXED at their spots. Nothing left to permute so we print. void RecursivePermute(char str[], int k) { int j; // Base-case: All positions are fixed, // Nothing to permute. if (k == strlen(str)) printf(%s\n, str);

Recursive Permutation Algorithm Recursive Permutation code in detail: Lets use CAT as our example Originally we call: RecursivePermute(CAT, 0) Since k == 0, ZERO characters are fixed, so we dont print yet. We move to the else case void RecursivePermute(char str[], int k) { int j; // Base-case: All positions are fixed, // Nothing to permute. if (k == strlen(str)) printf(%s\n, str); void RecursivePermute(char str[], int k) { // PREVIOUS CODE else { // Try each letter in spot j for (j=k; j<strlen(Str); j++) { // … }

Recursive Permutation Algorithm Recursive Permutation code in detail: ALL other cases (NON-base cases): Call this for loop Iterates the number of times EQUAL to the number of possible characters that can go into index k. // Try each letter in spot j for (j=k; j<strlen(Str); j++) { // Place next letter in spot k. ExchangeCharacters(str, k, j); // Print all perms with spot k fixed RecursivePermuite(str, k+1); // Put the old char back ExchangeCharacters(str, j, k); }

Recursive Permutation Algorithm Recursive Permutation code in detail: ALL other cases (NON-base cases): So it would try: – Permutations that start with C – Permutations that start with A – Permutations that start with T // Try each letter in spot j for (j=k; j<strlen(Str); j++) { // Place next letter in spot k. ExchangeCharacters(str, k, j); // Print all perms with spot k fixed RecursivePermuite(str, k+1); // Put the old char back ExchangeCharacters(str, j, k); }

Rec (CAT, 0) Rec (CAT, 1) Rec (CAT, 2) Rec (CAT, 3) Rec (ACT, 0) (CAT) Ex (CAT, 1,1) Ex (CAT, 1,2) Rec (CTA, 2) Ex (CAT, 2,2) Ex (CAT, 0,0) Ex (CTA, 2,2) Rec (CTA, 3) (CTA) Ex (CAT, 0,1) Ex (CAT, 0,2) Rec (ACT, 2) Rec (ACT, 3) (ACT) Ex (ACT, 1,1) Ex (ACT, 1,2) Rec (ATC, 2) Ex (ACT, 2,2) Ex (ATC, 2,2) Rec (ATC, 3) (ATC) Rec (TAC, 0) Rec (TAC, 2) Rec (TAC, 3) (TAC) Ex (TAC, 1,1) Ex (TAC, 1,2) Rec (TCA, 2) Ex (TAC, 2,2) Ex (TCA, 2,2) Rec (TCA, 3) (TCA) for (j=k; j<strlen(Str); j++) { ExchangeCharacters(str, k, j); RecursivePermute(str, k+1); ExchangeCharacters(str, j, k); }