All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars    
perplexus dot info

Home > Algorithms
Towers of Hanoi (Posted on 2003-09-07) Difficulty: 3 of 5
You have three small poles and five hoops - XS, S, M, L, XL (as in extra small, small, medium, large and extra large). They are placed on pole 1 in order, with largest at the bottom.

You can move one hoop at a time, and the hoops you are not moving have to be on a pole. You also cannot place a hoop on top of a smaller one. How can you move the hoops so that they are in the same order as they are now, but on pole 3?

See The Solution Submitted by Lewis    
Rating: 3.0667 (15 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
Some Thoughts C++ function | Comment 14 of 22 |
Here's a simple program in C++ to do the recursion, similar to Charlie's but it takes an input for each of the three poles (so you could call them A, B, and C or whatever) instead of hardcoding the numbering. Also, I made the output a separate function, so that if you wanted to diplay the output as the current state of the poles/hoops, perhaps using stacks to 'push' and 'pop' the hoops, you could do that. Mine right now just does the simple output anyway.
#include <iostream>

using namespace std;

void hanoi(int n, char src, char dst, char xtr);
void showMove(int n, char src, char dst);

void main() {
int n;
cout << \"Number of hoops: \";
cin >> n;
hanoi(n, 'A', 'B', 'C');
}

void hanoi(int n, char src, char dst, char xtr) {
// when there's just one left, put it where you want it
if (n==1) {
move(n,src,dst);
return;
}
// if there are more than 1, move all but last hoop to extra pole
hanoi(n-1, src, xtr, dst);
showMove(n,src,dst);
// after moving last hoop, put extra hoops back onto it
hanoi(n-1, xtr, dst, src);

}

void showMove(int n, char src, char dst) {
cout << \"Move \" << n << \" from \" << src << \" to \" << dst << endl;
}
  Posted by DJ on 2003-09-08 12:29:22
Please log in:
Login:
Password:
Remember me:
Sign up! | Forgot password


Search:
Search body:
Forums (1)
Newest Problems
Random Problem
FAQ | About This Site
Site Statistics
New Comments (6)
Unsolved Problems
Top Rated Problems
This month's top
Most Commented On

Chatterbox:
Copyright © 2002 - 2024 by Animus Pactum Consulting. All rights reserved. Privacy Information