【发布时间】:2021-09-20 14:04:44
【问题描述】:
问题:
- 函数内部的 For 循环返回一个莫名其妙的结果(第一张图片,在第 150 行以黄色突出显示)
- 在函数外部复制粘贴相同的 for 循环会返回预期结果(第二张图片,在第 164 行以紫色突出显示)
- 我不是在寻找有关算法问题方法的反馈 - 只是想了解上述内容
上下文:
- rock-paper-scissors 算法问题,返回一个嵌套数组数组,表示可能的手牌排列,基于作为参数传入的回合数
- 函数是递归的,以“n”轮作为参数,[[]] 作为默认参数
- 第 136 - 142 行:因为可能的总排列是 3 ^ n,所以它采用默认参数并将每个元素复制 3 次(newOutput)
- 第 146 - 149 行:for 循环通过 newOutput,将“rock”添加到第一个,“paper”添加到第二个,“scissors”添加到第三个嵌套数组,依此类推
问题
第 136 行元素的重复影响了第 146 行 for 循环的结果,但为什么呢?莫名其妙,因为执行线程已经移到第 146 行了。
代码如下:
function rockPaperScissors(num, output = [[]]) {
// when num is 0, return output
if (num === 0) return output;
const moves = ['rock', 'paper', 'scissors']
// take output parameter, and duplicate each of the existing nested array 3 times
const newOutput = output.reduce((acc, curr) => {
let i = 1;
while (i <= 3) {
acc.push(curr);
i++
}
return acc;
}, [])
// iterate through newOutput, push to each nested array rock first, then paper, then scissors, so on
for (let i = 0; i < newOutput.length; i++) {
newOutput[i].push(moves[i%3]);
}
return rockPaperScissors(num - 1, newOutput);
}
rockPaperScissors(1)
// should return [[rock], [paper], [scissors]]
// instead, returns [[rock, paper, scissors], [rock, paper, scissors], [rock, paper, scissors]]
【问题讨论】:
-
您图片中的代码有
newOutput[i].push(…),而您发布为文本的代码没有。 -
你从来没有使用过
moves数组,这些动作应该如何进入结果?
标签: javascript algorithm for-loop recursion reduce