More Recursion: Permutations and Towers of Hanoi

Slides:



Advertisements
Similar presentations
C++ Programming:. Program Design Including
Advertisements

More Recursion: Permutations and Towers of Hanoi COP 3502.
Recursion - see Recursion. RHS – SOC 2 Recursion We know that: –We can define classes –We can define methods on classes –Mehtods can call other methods.
HST 952 Computing for Biomedical Scientists Lecture 9.
Introduction to Data Structures and Algorithms Chapter 6 Recursion (1)
CS1101: Programming Methodology Recitation 9 – Recursion.
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.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
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.
16/23/2015 9:48 AM6/23/2015 9:48 AM6/23/2015 9:48 AMRecursion Recursion Recursion is when a function calls itself to implement an algorithm. Really a paradigm.
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.
Chapter 3: Arrays, Linked Lists, and Recursion
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Lists in Python.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
COSC 2006 Data Structures I Recursion II
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.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of 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.
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 6: Recursion Lecturer: Santokh Singh Assignment 1 due tomorrow. Should have started working.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Chapter 6 Questions Quick Quiz
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 15: Recursion. Recursive Definitions Recursion: solving a problem by reducing it to smaller versions of itself – Provides a powerful way to solve.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
1 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin.
Recursion - see Recursion
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Abdulmotaleb El Saddik University of Ottawa
Lesson #6 Modular Programming and Functions.
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
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.
Chapter 12 Recursion (methods calling themselves)
Recursion Chapter 11.
Fundamentals of Programming
Recursion - see Recursion
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
Lesson #6 Modular Programming and Functions.
Recursive Thinking.
Heaps Chapter 10 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates two.
Lecture 20 – Practice Exercises 4
Lecture 20 – Practice Exercises 4
Presentation transcript:

More Recursion: Permutations and Towers of Hanoi COP 3502

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 we’re 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: Permutations that start with C. Permutations that start with A. 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 don’t 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 there’s 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 // 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); So k refers to the first k characters that are fixed in their original positions.

Recursive Permutation Algorithm // 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); 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, there’s nothing left to permute So we just print out that permutation

Recursive Permutation Algorithm // 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); If we do NOT terminate: We want a loop that tries each character at index 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 1st 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 The string we want to permute (for example “CAT” 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: Let’s use “CAT” as our example Originally we call: RecursivePermute(“CAT”, 0) Since k == 0, ZERO characters are fixed, so we don’t print yet. We move to the else case void RecursivePermute(char str[], int k) { // PREVIOUS CODE else { // Try each letter in spot j for (j=k; j<strlen(Str); j++) { // … } 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: 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); }

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

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 So step 1 must be to move all disks above the bottom disk to the intermediate tower. In step 2, the bottom disk can now be moved to the destination tower. 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 Let’s 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. We’re 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 Start Temp Finish

Recursion – Towers of Hanoi The Towers of Hanoi Let’s 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 Start Temp Finish

Recursion – Towers of Hanoi The Towers of Hanoi Let’s 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 Start Temp Finish

1 3 2 5 4 6 7 Start Temp Finish Start Temp Finish 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 2n - 1 steps HUGE number

1 3 2 5 4 6 7 Start Temp Finish Start Temp Finish Start Temp Finish

3 7 4 Rec call to get here: Start Temp Finish Start Temp Finish Single move, just print. 4 Rec call to get here: Start Temp Finish 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);

// 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’); }