实现思路
- 将J、Q、K、A 分别用11、12、13、14 表示
- 排序
- 查找缺失位(比如3-4-5-6-7-9-10-J-Q-K,缺失位 8 检测缺失位前后是否有顺子,顺子连续大于5张)
class FindPlayingCards{
constructor() {
this.newCard = [];
this.temp = [];
this.straightList = [];
this.resoult = [];
}
init(str, cb) {
let list = Array.from(new Set(str.split("-")));
for (let i = 0; i < list.length; i++) {
let item = list[i];
if (Number(item)) {
this.newCard.push(Number(item));
} else {
if (item === "J") {
this.newCard.push(11);
} else if (item === "Q") {
this.newCard.push(12);
} else if (item === "K") {
this.newCard.push(13);
} else if (item === "A") {
this.newCard.push(14);
}
}
}
this.newCard = this.newCard.sort((a, b) => a - b);
let res = this.isStraight();
res.map((item, index) => {
let list = [];
if (item.length > 4) {
for (let i = 0; i < item.length; i++) {
if (item[i] === 11) {
list.push("J");
} else if (item[i] === 12) {
list.push("Q");
} else if (item[i] === 13) {
list.push("K");
} else if (item[i] === 14) {
list.push("A");
} else {
list.push(item[i]);
}
}
this.resoult.push(list);
} else {
cb("没有顺子");
}
});
cb(this.resoult);
}
isStraight() {
let list = this.newCard;
for (let i = list.includes(2) ? 1 : 0; i < list.length; i++) {
let stemp = list[i + 1];
let item = list[i];
/**
* temp 当这把牌有两以上的数顺子 是 第二个顺子是在第一个顺子基础上添加的
* [3,4,5,6,7]
* [3,4,5,6,7,9,0,10,11,12,13]
*
* */
* // 等差数列 后一项减去一个常数 等于 前一项
if (stemp - 1 !== item) {
/**
* 找出缺失的哪一项下标
* newCard.includes(2): 判断是否有 2,不参与顺子
* */
this.temp.push(list.slice(list.includes(2) ? 1 : 0, i + 1));
}
}
// 全部都是顺子
if (this.temp.length == 1) {
return this.temp;
}
this.temp.map((item, index) => {
if (index == 0) {
this.straightList.push(item);
} else {
this.straightList.push(item.slice(this.temp[index - 1].length));
}
});
return this.straightList.filter((item) =>
item.length > 4 ? item : []
);
}
}
测试
let str = "3-4-5-6-7-9-10-J-Q-K";
let findPalaingCards = new FindPlayingCards();
let html = "";
findPalaingCards.init(str, (res) => {
console.log(res)
/**
(2) [Array(5), Array(5)]
0: (5) [3, 4, 5, 6, 7]
1: (5) [9, 10, 'J', 'Q', 'K']
length: 2
[[Prototype]]: Array(0)
*/
});