Full House ในโป๊กเกอร์ = มีบัตร 3 ใบเหมือนกัน (three of a kind) โค้ดนี้ตรวจสอบว่ามี full house หรือไม่
ตัวอย่างโค้ด
const arr1 = ['A', 'A', 'A', 'K', 'Q']; // มี 3 A
const arr2 = ['K', '2', 'K', 'A', 'J']; // ไม่มี 3 ใบเหมือนกัน
const isFullHouse = arr => {
const copy = arr.slice();
for (let i = 0; i < arr.length; ) {
const el = copy.splice(i, 1)[0]; // ดึงเอาตัวที่ i ออก
if (copy.includes(el)) {
copy.splice(copy.indexOf(el), 1); // ลบตัวที่ 2
if (copy.includes(el)) { // มีตัวที่ 3
return true;
}
} else {
i++;
}
}
return false;
};
console.log(isFullHouse(arr1)); // true
console.log(isFullHouse(arr2)); // false
การทำงาน
- คัดลอกอาร์เรย์
- ดึงสมาชิกทีละตัว ตรวจสอบว่ามีซ้ำอีก 2 ตัวหรือไม่
- ใช้
spliceลบตัวที่เจอแล้วเพื่อไม่ให้นับซ้ำ
ผลลัพธ์
true false
หมายเหตุ: Full house จริงในโป๊กเกอร์คือ 3+2 (three of a kind + pair) โค้ดนี้ตรวจสอบแค่ 3 of a kind