20-Section-Handout

# 20-Section-Handout - CS106X Winter 2008 Handout 20 Section...

This preview shows pages 1–3. Sign up to view the full content.

CS106X Handout 20 Winter 2008 January 30, 2008 Section Handout: Recursion Problem 1: Towers Of Hanoi Revisited One of the procedural recursion problems we discussed in lecture was the classic Towers Of Hanoi problem. The recursive solution lists a series of moves needed to move a tower of disks from one location to a second. The solution I provided in class was: void MoveTower(int numDisks, string start, string dest, string temp) { if (numDisks > 0) { MoveTower(numDisks - 1, start, temp, dest); MoveDisk(start, dest); MoveTower(numDisks - 1, temp, dest, start); } } void MoveDisk(string start, string dest) { cout << "Move top disk from " << start << " to " << dest << "." << endl; } Consider the similar problem of moving another type of tower from the leftmost needle to the rightmost needle. A C A C Note that each size is represented twice: once as white and once as dark grey, and that the number of disks is always even. Note the alternating color scheme of the original tower must be re-established once the recursion is complete. So, the MoveTower function that solves this particular problem must ensure that: only one disk is moved at a time no disk is ever placed on top of a smaller disk

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 the alternating color scheme of the initial tower is re-established exactly in the final tower—that means grey on the bottom, and then white, grey, white, grey, etc. Here I provide you with four (possibly incorrect) versions of MoveTower . Indicate whether or not the particular implementation is valid, and briefly explain what the incorrect implementations will do. Version 1: MoveTower(int numDisks, string start, string dest, string temp) { if (numDisks > 0) { MoveTower(numDisks - 1, start, temp, dest); MoveDisk(start, dest); MoveTower(numDisks - 1, temp, dest, start); } } Correct Incorrect Simply imagine the white disks as being the slightest bit smaller than their dark grey cousins. Then we have the same type of tower as we dealt with in class (to see this, forget about the fact that the disks are colored. Version 2: MoveTower(int numDisks, string start, string dest, string temp) { if (numDisks > 0) { MoveTower(numDisks - 2, start, temp, dest); MoveDisk(start, dest); MoveDisk(start, dest); MoveTower(numDisks - 2, temp, dest, start); } } Correct Incorrect This will not work. Even if we trust the recursion to move the tower of height numdisks - 2 correctly, it should be clear that the largest white disk will sit
This is the end of the preview. Sign up to access the rest of the document.

## 20-Section-Handout - CS106X Winter 2008 Handout 20 Section...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online