I am having trouble with an iterative solution to the Towers of Hanoi puzzle. As this was a university task, we have been given pseudo-code to follow.
Towers(number, src, dest, alt)
begin
push { number, src, dest, alt }
while NOT stack.empty
pop { number, src, dest, alt }
if number = 1
print "Move 1 disc from " + src + " to " + dest
else
push { number – 1, alt, dest, src }
push { 1, src, dest, alt }
push { number – 1, src, alt, dest }
end-if
end-while
end
This is my attempt in C#:
static void TowersIterative(uint number, char src, char dest, char alt)
{
Stack<Move> _Stack = new Stack<Move>();
_Stack.Push(new Move(number, src, dest, alt));
while (_Stack.Count != 0)
{
_Stack.Pop();
if (number == 1)
Console.WriteLine("Move one disc from {0} to {1}", src, dest);
else
{
_Stack.Push(new Move(number - 1, alt, dest, src));
_Stack.Push(new Move(1, src, dest, alt));
_Stack.Push(new Move(number - 1, src, alt, dest));
}
}
}
Nothing much is going on with the move class at the moment.
class Move
{
private char _Src, _Alt, _Dest;
private uint _Number;
public Move(uint number, char src, char dest, char alt)
{
_Number = number;
_Src = src;
_Alt = alt;
_Dest = dest;
}
}
This is an example of the desired output when number = 3
, src = 'L'
, alt = 'M'
, and dest = 'R'
:
Move one disc from L to M
Move one disc from L to R
Move one disc from M to R
At the moment, the while loop in the TowersIterative
method infinitely loops, and the number variable never equals 1.