I am stuck on the following function which appears in a few other posts I've also reviewed.
function findSequence(goal) {
function find(start, history) {
if (start == goal)
return history;
else if (start > goal)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
print(findSequence(24));
Also given in this link.
Javascript..totally lost in this tutorial
In the above explanation, the answer instead tried to set a goal of 11. They have a start of 1, which is first tested against 11, and then a start of 6 which is tested against 11.
I understand these first two steps. However, I do not understand the leap from the 2nd step (comparing start
:6 to goal
:11) to the third step (comparing start
:3 to goal
:11).
How does start
go from 6, back down to 3, and then back up to 11 (fourth bullet)?
Ok, here is a version of the code which was enhanced with console log statements. Open Chrome/Opera/Firefox eveloper tools and execute this code there:
function findSequence (goal) {
function find (start, history, depth) {
depth = depth || 0;
console.log( Array( ++depth ).join('--> '), start, goal, history );
if (start == goal) {
console.warn( 'history' );
return history;
} else if (start > goal) {
console.error( 'null' );
return null;
} else {
console.info('recursion!');
return find(start + 5, "(" + history + " + 5)", depth) ||
find(start * 3, "(" + history + " * 3)", depth);
}
}
return find(1, "1");
}
console.info( findSequence(24) );
You will get a call trace of this program, and hopefully will grasp the concept of recursion visually, by looking on the trace.
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