按組重新排列卡牌


問題

你需要編寫一個 JavaScript 函式,該函式的第一個引數是數字陣列 arr,第二個引數是數字 num。

陣列中的數字範圍為 [1, 13],邊界值包含在內,表示紙牌的從 1 開始的索引。

你的函式應該確定是否有一種方法可以將紙牌重新排列成組,使得每組大小為 num,且由 num 張連續的紙牌組成。

例如,如果函式的輸入如下

輸入

const arr = [1, 4, 3, 2];
const num = 2;

輸出

const output = 2;

輸出說明

因為紙牌可以重新排列為 [1, 2], [3, 4]

示例

以下是程式碼 −

 線上演示

const arr = [1, 4, 3, 2];
const num = 2;
const canRearrange = (arr = [], num = 1) => {
   const find = (map, n, num) => {
   let j = 0
   while(j < num) {
      if(!map[n + j]) return false
         else map[n + j] -= 1
         j++
      }
      return true
   }
   let map = {}
   arr.sort(function(a, b) {return a - b})
   for(let n of arr) {
      map[n] = map[n] ? map[n] + 1 : 1
   }
   for(let n of arr) {
      if(map[n] === 0 || find(map, n, num)) continue
         else return false
   }
   return true
};
console.log(canRearrange(arr, num));

輸出

true

更新於: 2021-04-24

108 次瀏覽

開啟您的 職業生涯

完成該課程以獲得認證

開始學習
廣告