Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Tower of hanoi

Ravi Sathish
Ranch Hand
Posts: 131
Hi guys this is a small program abt Tower of Hanoi...(if u don't wat the prblem is plz mail me I'll give the explanation for tower of Hanoi)
But my real worry is when the same logic is tried in 'C' the program works fine for recursion...
But when it is implemented in java..O/p is terribly out of place..Can u plz suggest ways to achieve the result???
I am including the code here...
TIA
ravi
class TowerOfHanoi
{
void tower(int n, char a, char b, char c)
{
// this is a recursive function which calls itself
if (n>0)
{
tower(n-1,'a','c','b');
System.out.println("Move disk "+n+" from "+ a +" to "+ b +" via "+c);
tower(n-1,'c','b','a');
}
}
public static void main(String args[])
{
tower(3,'a','b','c');
}
}

Chris Pocock
Greenhorn
Posts: 13
What's this program meant to do? I copied it, then just changed a couple of things so I could compile it as a C++ console app, but just gives me the following when its executed:
Move disk 1 from a to c via b
Move disk 2 from a to c via b
Move disk 1 from c to b via a
Move disk 3 from a to b via c
Move disk 1 from a to c via b
Move disk 2 from c to b via a
Move disk 1 from c to b via a

Have I done something wrong while trying to convert it myself or am I just too much of a newbie in Java to know what the heck i'm doing with this...
BTW What's the Tower of hanoi?

Ravi Sathish
Ranch Hand
Posts: 131
Hey tower of hanoi is a old puzzle...
here u have disks('n' no.. of them)on pole a.. of different sizes arranged from biggest one(highest number here 3) at the bottom to smallest one(lower number here 1)at the top...
the solution is to move the disks from pole a to pole b using c as an intermediate pole..
any number of moves is allowed but always a smaller disk should be on top of the bigger disk..
hope this helps...

Rish Gupta
Greenhorn
Posts: 29
I think this should work :

Rish Gupta
Greenhorn
Posts: 29
This should explain the process with an output (please let me know if I can somehow make it more efficient):