Good day. I have a challenge when it comes to tracking how parameter values change in JavaScript recursion. Attached is a JavaScript function “createPartitions()” that determines the possible combinations of the sum of integers that make up a particular number (e.g. 4 => 1111, 121, 22, 13, 4). The code is succinct but I have added console.log() at specific points to capture how the parameter values change for every cycle.
The first 8 cycles are pretty straightforward with maxValue decreasing by 1 and then target later reducing by 1. The challenge for me starts from the 10th line (where target begins to increase by 1), all the way to the end. Please try to shed light on how the arguments target and maxValue change values in the recursion
let i=0;
function createPartitions(target, maxValue, suffix, partitions) {
i++;
if (target == 0) {
console.log("A :" + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
partitions.push(suffix);
} else {
if (maxValue > 1) {
console.log("B :" + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
createPartitions(target, maxValue-1, suffix, partitions);
}
if (maxValue <= target) {
console.log("C :" + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
createPartitions(target-maxValue, maxValue, [maxValue, ...suffix], partitions);
}
console.log("D :" + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
}
console.log("E : " + "target : " + target + " maxValue : " + maxValue + " " + "suffix: " + JSON.stringify(suffix));
}
const partitions = [];
createPartitions(4, 4, [], partitions);
console.log(partitions);
// console.log(i);
Here are the screenshots of the log. The 10th line (marked by red border) is where it starts to get tricky for me.