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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With