Towers of Hanoi - Part 2
We just covered the Towers of Hanoi for Case 1 and Case 2, let's return to 3 disks. Can you describe an algorithm to move the 3 disks from a starting peg to the goal peg? You can refer back to solved cases when needed.
- Move the top 2 disks to the intermediate peg. How? Refer to Case 2.
- Move the bottom Disk to the Goal Peg. (See case 1)
- Move the 2 disks from the intermediate peg to the goal peg. How? Refer to Case 2.
Now that we've covered 1, 2 and 3 disks, can you figure out an algorithm for solving the towers of Hanoi for any number of N disks?
- Move the top N-1 disks to the intermediate peg. How? Refer to Case N-1.
- Move the bottom Disk to the Goal Peg. (See case 1)
- Move the N-1 disks from the intermediate peg to the goal peg. How? Refer to Case N-1.
To solve it for N disks, you just move N-1 disks off. How do you move them? Refer to N-1-1. How do you solve that? Just refer to the case below that... Keep on going until you reach a base case. Then the results will return up the stack and you'll get a complete answer.
Sound familiar? This is similar to how Factorial was calculated, and is a classic case of Recursion. In this case recursion is crucial, since it would be quite difficult to follow the same algorithm without it.
Challenge
Create a program that solves the tower of Hanoi. You will be given one number as input - the number of disks on Peg 1. Create and call a method that prints out the correct steps to solve the puzzle.
Output Format:
Print the peg to move from, an arrow "->", and the peg to move to. For example, to move from peg 1 to peg 3, print:
1->3
.
Print all the steps for a given case on its own line.
Challenge
Create a program that solves the Towers of Hanoi and prints out the solution.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
曾國峻
Feb 13, 8:49 AMAlthough I know the process of solution to the problem, I can't figure out how to transform into program. Could anyone give me some hint of how to program it?
Learneroo
Feb 13, 7:54 PMYou can view the beginning of a solution here. The comments there can help guide you to a full solution.
曾國峻
Feb 13, 8:32 PMThanks, I have finished the challenge with your hint.
mike
Aug 16, 5:43 PM