-1

I've been trying to create a program to solve the towers of hanoi using recursive thinking. I've looked online a lot and cannot figure out why the code keeps printing out the wrong thing. Here is what I have so far:

public static void tower(int start, int finish, int helper, int number)
      {
         if(number == 1)
            System.out.println("Move disk 1 from "+start+" to "+finish+".");
         else
         {
            tower(start, finish, helper, (number - 1));
            System.out.println("Move disk "+number+" from "+start+" to "+finish+".");
            tower(helper, start, finish, (number - 1));
         }      
      }
   }

but it keeps printing out:

Move disk 1 from 1 to 3.
Move disk 2 from 1 to 3.
Move disk 1 from 2 to 1.
Move disk 3 from 1 to 3.
Move disk 1 from 2 to 1.
Move disk 2 from 2 to 1.
Move disk 1 from 3 to 2.

Any suggestions?

aioobe
  • 413,195
  • 112
  • 811
  • 826
J Doe
  • 11
  • 1
  • 2
    I was going to indent the code, but you have more closing braces than opening braces. Can you check that the code you copied is correct? Also, we will need to see how you are calling this function to really answer your question. Please read this page to understand what we need from you to give a good answer: http://stackoverflow.com/help/mcve – Brendan Long May 09 '16 at 18:59
  • First, are you certain it is `number == 1` and not `number == 0`? Generally if you have, e.g., 3 disks, they will be 0, 1, 2. Second, it looks like the recursive parameters are wrong. For example, I *think* (without doing a lot of debugging), the first recursive call should be `tower(start, helper, finish, (number - 1));`. You should carefully examine the algorithm here. – KevinO May 09 '16 at 19:12

1 Answers1

0

This should work :

public static void tower(int start, int finish, int helper, int number)
      {
         if(number == 1)
            System.out.println("Move disk 1 from "+start+" to "+finish+".");
         else
         {
            tower( start, helper, finish, number-1);
            System.out.println("Move disk "+number+" from "+start+" to "+finish+".");
            tower( helper, finish, start, number - 1);
         }      
      }

Output for tower(1, 3, 2, nDisks); :

Move disk 1 from 1 to 3.
Move disk 2 from 1 to 2.
Move disk 1 from 3 to 2.
Move disk 3 from 1 to 3.
Move disk 1 from 2 to 1.
Move disk 2 from 2 to 3.
Move disk 1 from 1 to 3.
Ani Menon
  • 27,209
  • 16
  • 105
  • 126