簡體   English   中英

使用遞歸交錯兩個數組(卡片組)......我能夠在沒有遞歸的情況下解決它,但想知道我做錯了什么

[英]Interleave two arrays (card decks) using recursion... I was able to solve it without recursion but want to know what I am doing wrong

我正在嘗試編寫一個函數,它將兩個數組作為輸入,代表一副紙牌的上半部分和下半部分,並使用遞歸將它們洗牌在一起。 我正在嘗試返回一個數組,其中包含來自交錯的兩個輸入數組的元素,如下所示:

  • 第一個元素應該是第一個輸入數組的第一個元素
  • 第二個元素應該是第二個輸入數組的第一個元素,
  • 第三個元素應該是第一個輸入數組的第二個元素,
  • 第四個元素應該是第二個數組的第二個元素,

...等等。

我想將任何剩余的元素附加到數組的末尾。

這就是我在沒有遞歸的情況下解決它的方法:

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 ? [] : [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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM