While studying eloquent JavaScript, I encountered a program that checks whether any combination of multiplying 3 and adding 5 produces the target value:
However, this function does not provide the shortest possible sequence for achieving the target value.
I am struggling to figure out the logic needed to obtain the shortest possible solution. How can I modify this code to generate the shortest path?
function find_solution(target) {
function find(current, history) {
if (target === current) {
return history;
} else if (target < current) {
return null;
} else {
return find(current + 5, `(${history} + 5)`) || find(current * 3, `(${history} * 3)`);
}
}
return find(1, '1');
}
console.log(find_solution(24));