Skip to content

Instantly share code, notes, and snippets.

@json2d
Created June 19, 2018 20:51
Show Gist options
  • Save json2d/6b53ee2a6dfc8947613be4c7bf9141da to your computer and use it in GitHub Desktop.
Save json2d/6b53ee2a6dfc8947613be4c7bf9141da to your computer and use it in GitHub Desktop.
Poker hand classification and comparison
// [{suit:1,val:2}] -> 2 of diamonds
function isFlush(a) {
let suit, result = true;
for(var i=0; i<a.length;i++){ //should use a forloop to break early
const card = a[i]
if(suit===undefined) {
suit = card.suit
}else if(suit !== card.suit){
return false
}
})
return true;
}
function isStraight(a) {
let cur = a[0].val
for(var i=1;i<a.length;i++) {
if(a[i].val !== cur+1) {
return false;
}
cur = a[i].val;
//cur ++;
}
return true
}
function isStraightFlush(a) {
return isFlush(a) && isStraight(a)
}
function isRoyalFlush(a) {
const is10 = a[0].val === 10
return is10(a) && isFlush(a)
}
function isFourOfAKind(a) {
return isNOfAKind(a,4)
}
function isThreeOfAKind(a) {
return isNOfAKind(a,3)
}
function isNOfAKind(a,n) {
let counts = {}
a.forEach((card) => {
if(counts[card.val] === undefined) {
counts[card.val] = 1;
}else{
counts[card.val]++
}
})
const vals = Object.values(counts)
for(var i = 0; i< vals.length; i++) {
if(vals[i] === n) {
return true
}
}
return false
}
function isFullHouse(a) {
return isNOfAKind(a,3) && isNOfAKind(a,2)
}
function numberOfPairs(a) {
let counts = {}
a.forEach((card) => {
if(counts[card.val] === undefined) {
counts[card.val] = 1;
}else{
counts[card.val]++
}
})
const vals = Object.values(counts)
const pairs = 0;
for(var i = 0; i< vals.length; i++) {
if(vals[i] === 2) {
pairs++
}
}
return pairs
}
function isTwoPair(a) {
return numberOfPairs(a) === 2;
}
function isOnePair(a) {
return numberOfPairs(a) === 1;
}
function isHighCard(a) {
return true;
}
const classifications = [
isRoyalFlush,
isStraightFlush,
isFourOfAKind,
isFullHouse,
isFlush,
isStraight,
isThreeOfAKind,
isTwoPair,
isOnePair,
isHighCard
]
function compareHands(a,b) {
const aS = scoreHand(a), bS= scoreHand(b);
if (aS === bS) {
return undefined
}else if(aS < bS) {
return a
}else{
return b
}
}
function scoreHand(a) {
for(var i=0;i<classifications.length;i++) {
if(classifications[i](a)) {
return i;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment