This is a recursive function to show on the screen how to obtain X number through a mathematical calculation where you can only sumar 5 (+5)
or multiplicar por 3 (*3)
, having as base the number 1:
Example:
If I want to get to 13 from 1, first multiply by 3, then add 5 and then again add 5.
findSolution(13) === (((1 * 3) + 5) + 5)
Javascript code:
function findSolution(target) {
function find(current, history) {
if (current == target)
return history;
else if (current > target)
return null;
else
return find(current + 5, "(" + history + " + 5)") ||
find(current * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
console.log(findSolution(13));
(((1 * 3) + 5) + 5)
Iterating only using +5:
6,1
11,1
16,1
null
Iterando multiplying by 3:
3,1
9,1
27,1
null
So I would like to know: How does the return find() || find()
work ?, since I do not know how the function works to decide between +5 or * 3, or if it automatically generates two calls to FIND each time you make a return, and in turn two calls per option ?, something similar to the following tree: