I have dabbled in coding for a while now and have justs recently started teaching myself JavaScript. I am using a few sources to learn from, and one of them had me program a hanoi tower game. Everything is working according to plan, I just cant figure out how its working. Why is it turning out the way it is. If someone could explain this to me it would be great.
Thanks in advance,
Danny Bussell
here is the code…
var hanoi = function hanoi(disc, src, aux, dst)
{
if (disc > 0)
{
hanoi(disc – 1, src, dst, aux);
document.writeln(‘Move disc ‘ +
disc + ‘ from ‘ + src + ‘ to ‘ + dst);
hanoi(disc – 1, aux, src, dst);
}
};
hanoi(3, ‘Src’, ‘Aux’, ‘Dst’);
–and here is the output…
Move disc 1 from Src to Dst
Move disc 2 from Src to Aux
Move disc 1 from Dst to Aux
Move disc 3 from Src to Dst
Move disc 1 from Aux to Src
Move disc 2 from Aux to Dst
Move disc 1 from Src to Dst
Whats confusing me:
When the function is called, it is setting the ‘disc’ to 3. The first thing being done after it realizes 3>0 is to subtract 1 from ‘disc’. Directly after that, it writes the line. So I dont get how the first line of the output is showing “disc 1” is moved instead of “disc 2” (3-1=2 is my logic). Anther thing, (you cant see it here for lack of tabs) the first line of output “Move disc 1…” is tabbed over 2 or 3 times…dont know why. Its not really my main concern here, but it baffles me non-the-less.
I have really been trying to understand the reasoning behind the output of code and am not wanting to go further learning till I can understand and apply this correctly.
Thanks to whoever answers this, I have a few more questions on this chunk of coding, but really wanted to get this one answered. So if someone knowledged decides to take a whack at answering this one, I would not mind a more detailed explanation if you wish.
Thanks again