My introductory tutorial has suddenly become very advanced. I have no idea how this program works. Can you explain in plain language?
At the end it prints (((1 * 3) + 5) * 3), but I don’t get it at all. I understand that findSequence gets passed 24, that triggers function find. I’m assuming that function find gets passed 1,”1″ with the latter being assigned to history?? but I don`t understand why the second 1 is in quotation marks “1!, nor do I understand the use of quotation marks when it returns find(start etc.
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));
You have an “output” string
(((1 * 3) + 5) * 3), a goal24and a first character1. The1is the 1 in1 * 3. This program will assemble a string containing a math expression, adding (), *3 and +5 to try to obtain the goal. The two parameters of thefindfunction are the current total and the expression that will generate the total. Clearly the expression is a string. The find compares the current total to the goal, and if it’s equal then the expression is correct and it returns it, if the current total is > of the goal then he failed and return null. Otherwhise he add some operations to the expression. He tries two “ways”, one multiplying * 3 the current result, the other adding +5 to the current result. It’s recursive on a tree (so each time he will bifurcate in two recursive calls). null || something == something, so the branch that will find a response will return his response, the other branch will return null and the “winning” response will be passed back.Let’s say the goal is 11.
To make it even clearer, try these versions:
And this, where instead of an expression you’ll get only as tring of + and *
And be aware that, as an example, it’s quite complex because it used closures (locally defined functions).