Untitled
const SUITS = ["clubs", "hearts", "diamonds", "spades"] const RANKS = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "Joker" ] class Card { constructor(suit, rank) { this.suit = suit this.rank = rank } } function isValidHand(cards) { if (cards.length != 5) return false let ranks = new Map() let suits = new Map() let jokerCount = 0 for (let i = 0; i < cards.length; i++) { if (cards[i].rank == "Joker") { jokerCount++ continue } if (!ranks.has(cards[i].rank)) { ranks.set(cards[i].rank, 1) } else { let temp = ranks.get(cards[i].rank) ranks.set(cards[i].rank, temp + 1) } if (!suits.has(cards[i].suit)) { suits.set(cards[i].suit, 1) } else { let temp = suits.get(cards[i].suit) suits.set(cards[i].suit, temp + 1) } } if (jokerCount == 5) return true let rankFrequencies = [...ranks.values()] let rankValues = [...ranks.keys()] // Flush - makes straight flush redundant if (suits.size == 1) return true // 4 of a kind - makes 5 of a kind redundant for (let i = 0; i < rankFrequencies.length; i++) { if (rankFrequencies[i] + jokerCount >= 4) return true } // Full House if (jokerCount == 0) { if (ranks.size == 2 && (rankFrequencies[0] == 2 || rankFrequencies[0] == 3)) return true } else if (jokerCount == 1) { if (ranks.size == 2) return true } else if (jokerCount == 2 || jokerCount == 3) { if (ranks.size == 1 || ranks.size == 2) return true } else if (jokerCount > 3) return true // Straight if (rankValues.length + jokerCount != 5) return false let weightArr = [] for (let i = 0; i < rankValues.length; i++) { weightArr.push(RANKS.indexOf(rankValues[i])) } weightArr.sort((a, b) => a - b) if (weightArr[weightArr.length - 1] - weightArr[0] < 5) return true return false }
Leave a Comment