使用递归交错两个数组(卡片组)..我能够在没有递归的情况下解决它,但我想知道我做错了什么



我正试图编写一个函数,该函数以两个数组作为输入,表示一副牌的上半部分和下半部分,并使用递归将它们混洗在一起。我正在尝试返回一个数组,其中包含交错的两个输入数组中的元素,如下所示:

  • 第一个元素应该是第一个输入的第一个元素阵列
  • 第二个元素应该是第二个输入的第一个元素阵列
  • 第三个元素应该是第一个输入的第二个元素阵列
  • 第四元素应当是第二阵列的第二元素

。。。等

我想将所有剩余的元素附加到数组的末尾。

这就是我在没有递归的情况下解决它的方法:

function shuffleCards(topHalf, bottomHalf) {
let returnArray = [];
for (let i = 0; i < Math.max(topHalf.length, bottomHalf.length); i++) {
if (topHalf[i]) {
returnArray.push(topHalf[i]);
}
if (bottomHalf[i]) {
returnArray.push(bottomHalf[i]);
}
}
return returnArray
}

这是我对递归的尝试:

function shuffleCards(topHalf, bottomHalf) {
let results = [];
if (topHalf.length) {
results.push(topHalf[0]
} 
if (bottomHalf.length) {
results.push(bottomHalf[0])
}
return results.concat(shuffleCards(topHalf.slice(1), bottomHalf.slice(1)));
}

我不断地得到语法错误";缺少(在参数列表"之后;但我可以肯定所有的括号都在书写的地方。

有什么建议吗?

谢谢!

除了缺少括号外,您只能从前半部分中获取第一项,并使用交换的数组调用函数。

function shuffleCards([value, ...topHalf], bottomHalf) {
return value === undefined
? [...bottomHalf]
: [value, ...shuffleCards(bottomHalf, topHalf)];
}
console.log(...shuffleCards([1, 2, 3, 4], [5, 6, 7, 8]));

function shuffleCards(topHalf, bottomHalf,results = []) {
if(topHalf.length===0&&bottomHalf.length===0)return results;
if (topHalf.length!==0) {
results.push(topHalf[0])
} 
if (bottomHalf.length!==0) {
results.push(bottomHalf[0])
}
return shuffleCards(topHalf.slice(1), bottomHalf.slice(1),results);
}

最新更新