如何在 JavaScript 递归中跟踪变量的值

问题描述 投票:0回答:1

在跟踪 JavaScript 递归中参数值如何变化时,我遇到了挑战。附件是一个 JavaScript 函数“createPartitions()”,它确定组成特定数字的整数总和的可能组合(例如 4 => 1111, 121, 22, 13, 4)。代码很简洁,但我在特定点添加了 console.log() 来捕获每个周期的参数值如何变化。

前 8 个周期非常简单,maxValue 减少 1,然后 target 减少 1。对我来说,挑战从第 10 行开始(其中 target 开始增加 1),一直到最后。请尝试阐明参数 target 和 maxValue 如何在递归中更改值

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);
.as-console-wrapper { max-height: 100% !important; top: 0; }

以下是日志截图。第 10 行(用红色边框标记)对我来说开始变得棘手。

enter image description here

enter image description here

javascript loops recursion combinations partitioning
1个回答
0
投票

你的问题有点不清楚。如果下面的方法对你有效的话,你可以尝试一下。请参考以下代码:

let i = 0;

function createPartitions(target, maxValue, suffix, partitions, depth = 0) {
  const indent = "  ".repeat(depth);
  i++;
  if (target == 0) {
    console.log(`${indent}A: target=${target}, maxValue=${maxValue}, suffix=${JSON.stringify(suffix)}`);
    partitions.push(suffix);
  } else {
    if (maxValue > 1) {
      console.log(`${indent}B: target=${target}, maxValue=${maxValue}, suffix=${JSON.stringify(suffix)}`);
      createPartitions(target, maxValue - 1, suffix, partitions, depth + 1);
    }
    if (maxValue <= target) {
      console.log(`${indent}C: target=${target}, maxValue=${maxValue}, suffix=${JSON.stringify(suffix)}`);
      createPartitions(target - maxValue, maxValue, [maxValue, ...suffix], partitions, depth + 1);
    }
    console.log(`${indent}D: target=${target}, maxValue=${maxValue}, suffix=${JSON.stringify(suffix)}`);
  }
  console.log(`${indent}E: target=${target}, maxValue=${maxValue}, suffix=${JSON.stringify(suffix)}`);
}


const partitions = [];
createPartitions(4, 4, [], partitions); 
console.log(JSON.stringify(partitions)); // Initialize and call the function
console.log(`Total iterations: ${i}`);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.