Towers of Hanoi - Part 2


Collapse Content

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.

The Algorithm for 3 Disks

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?

towers of turtles

The Algorithm for N Disks

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

  • Although 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?

  • You can view the beginning of a solution here. The comments there can help guide you to a full solution.

  • Thanks, I have finished the challenge with your hint.

  •     public static void doStuff(int a){
        solve(1, 3, a);
        System.out.println();
    }
    
    static void solve(int a, int b, int elements){
    
    cont...
All Node Comments
Contact Us
Sign in or email us at [email protected]