按組重新排列卡牌
問題
你需要編寫一個 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP