File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Tower of hanoi Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Tower of hanoi" Watch "Tower of hanoi" New topic
Author

Tower of hanoi

Ravi Sathish
Ranch Hand

Joined: Feb 26, 2002
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

Joined: Mar 11, 2002
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?


<i>I'm currently reading 'How to program Java' by Deitel</i><br /><b>I am still learning, so be kind. I also know C++, by the way</b>
Ravi Sathish
Ranch Hand

Joined: Feb 26, 2002
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

Joined: Sep 29, 2011
Posts: 29
I think this should work :
Rish Gupta
Greenhorn

Joined: Sep 29, 2011
Posts: 29
This should explain the process with an output (please let me know if I can somehow make it more efficient):
 
jQuery in Action, 2nd edition
 
subject: Tower of hanoi