# The Tower of Hanoi problem

I need to write a shell script on a Sun system in K-shell that solves the Tower of Hanoi Problem.  It must use a recursive function.  I'm stumped.

Sorry, perhaps I should have elaborated.  I have a sample program written out for this problem.  I have the function already set up and it does call itself.  The problem lies in the fact that it doesn't move the disks in the right order.
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
most of the recursive function can be replaced by using loops.
0
Commented:
Sounds like a homework problem.  How about a hint?

The k-shell provides for function definitions.  So in your script you can define one like:

function blah
{
# Do some stuff
}

So it follows that you can have blah call itself recursively:

function blah
{
# Do some stuff
blah

# Do some more stuff
}

Don't forget that somewhere you have to test whether blah needs to be called again.  Otherwise, you'll just keep calling blah until the computer's memory runs out.
0
Author Commented:
Edited text of question
0
Commented:
Obviously you've programmed it wrong.  Program it correctly and it's likely to work.  From what you've posted, I don't see that any more definitive help is possible.
0
Commented:
Show me your code and I'll try to fix it (I know next to nothing about the ksh, so
I need your syntax first ;-) In pseudo code:

# from, to == 1, 2, 3, size >= 0
function Hanoi(from, to, size) {

if (size) {
Hanoi(from, 6-from-to, size-1);
move(from, to);
Hanoi(6-from-to, to, size-1);
}

kind regards,

Jos aka jos@and.nl

0
Commented:
There are also a range of non-recursive solutions to the towers
of hanoi problem. A stack should not be too hard to improvise if
the syntsx is something close to a bourne shell--just use a stack
pointer (i.e. counter) and eval to get the right number of levels
of shell expansion. This probably leaves some values around but
unset fixes that if you want the fineese. [I would be unlikely to
bother myself].
0
Commented:
#!/bin/ksh

# A recurssive function to perform the moves
hanoi()
{
if [ \$1 -ne 0 ]
then
hanoi `expr \$1 - 1` \$2 \$4 \$3
echo "Move disk \$1 from peg \$2 to peg \$3"
hanoi `expr \$1 - 1` \$4 \$3 \$2
fi
}

#main program
echo "Enter the number of disks :"
if [ "\$x" -ge 0 ]
then
# Call hanoi to move N disks from peg A to peg C
# using peg B
hanoi \$x A C B
else
echo Its invalid
fi 2>/dev/null

0

Experts Exchange Solution brought to you by