Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tower Of Hanoi - JavaScript - THe Good Parts [duplicate]

I have seen the other Questions on SO about the Recursive function and I have read the responses but I still can't get the algorithm to click in my head

var hanoi = function (disc, src, aux, dst) {

  if (disc > 0) {
    hanoi(disc - 1, src, dst, aux);
   document.write('Move disc ' + disc + ' from ' + src + ' to ' + dst);
    hanoi(disc - 1, aux, src, dst);
  }
}

hanoi(3, 'Src', 'Aux', 'Dst');

How does the document.write(...), ever run. My Logic is First time we run the function disc is > 3. then we recursively call the function again skipping everything below so how does the document.write get a chance to run?

I understand recursion (done the basic examples) but i still can't see how you get an output. If there is a way i can run it visually and see it in action, that would help alot.

like image 645
Mike Diaz Avatar asked Aug 15 '11 01:08

Mike Diaz


1 Answers

You can think of what will happen as a call tree (time moves from top to bottom):

hanoi(3, ...) =>
 |-> hanoi(2, ...) =>
 |    |-> hanoi(1, ...) =>
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |    |-> document.write(...)
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |  <-/ [hanoi(1, ...) finished]
 |    |-> document.write(...)
 |    |-> hanoi(1, ...) =>
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |    |-> document.write(...)
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |  <-/ [hanoi(1, ...) finished]
 |  <-/ [hanoi(2, ...) finished]
 |-> document.write(...) [halfway done!]
 |-> hanoi(2, ...) =>
 |    \-> [same pattern as the first time, with different data]
 \-> [hanoi(3, ...) finished]
like image 150
Ted Hopp Avatar answered Nov 15 '22 14:11

Ted Hopp