Last active
July 20, 2022 05:09
-
-
Save msimpson/19715873215ca0aa862c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// Test Hand | |
var hand = [ | |
{ rank: 10, suit: 1 }, | |
{ rank: 11, suit: 1 }, | |
{ rank: 12, suit: 1 }, | |
{ rank: 13, suit: 1 }, | |
{ rank: 14, suit: 1 } | |
]; | |
// Histogram | |
// { rank : count } | |
var histogram = hand.reduce( ( histogram, card ) => { | |
histogram[ card.rank ] = ( histogram[ card.rank ] || 0 ) + 1; | |
return histogram; | |
}, {} ); | |
// Scored Histogram | |
// (descending by count) | |
// [ [ rank, count ] ] | |
var scoredHistogram = | |
Object | |
.keys( histogram ) | |
.map( rank => [ parseInt( rank ), histogram[ rank ] ] ) | |
.sort( ( a, b ) => a[ 1 ] == b[ 1 ] ? a[ 0 ] < b[ 0 ] : a[ 1 ] < b[ 1 ] ); | |
// Suits | |
// [ suit : count ] | |
var suits = hand.reduce( ( suits, card ) => { | |
suits[ card.suit ]++; | |
return suits; | |
}, [ 0, 0, 0, 0 ] ); | |
// Ranked Hand | |
// (descending by rank) | |
// [ index : rank ] | |
var rankedHand = hand.map( card => card.rank ).sort( ( a, b ) => a - b ); | |
// Scoring | |
var isFlush = suits.indexOf( 5 ) >= 0; | |
var isWheel = rankedHand[ 4 ] === 14 && rankedHand[ 0 ] === 2; | |
var isStraight = ( | |
rankedHand[ 4 ] - rankedHand[ 3 ] === 1 || isWheel | |
) && ( | |
rankedHand[ 3 ] - rankedHand[ 2 ] === 1 && | |
rankedHand[ 2 ] - rankedHand[ 1 ] === 1 && | |
rankedHand[ 1 ] - rankedHand[ 0 ] === 1 | |
); | |
console.log( | |
isStraight && isFlush && rankedHand[ 4 ] === 14 && !isWheel ? 'Royal Flush' | |
: isStraight && isFlush ? `Straight Flush ${ isWheel ? '( Wheel )' : '' }` | |
: scoredHistogram[ 0 ][ 1 ] === 4 ? 'Four of a Kind' | |
: scoredHistogram[ 0 ][ 1 ] === 3 && scoredHistogram[ 1 ][ 1 ] === 2 ? 'Full House' | |
: isFlush ? 'Flush' | |
: isStraight ? `Straight ${ isWheel ? '( Wheel )' : '' }` | |
: scoredHistogram[ 0 ][ 1 ] === 3 && scoredHistogram[ 1 ][ 1 ] === 1 ? 'Three of a Kind' | |
: scoredHistogram[ 0 ][ 1 ] === 2 && scoredHistogram[ 1 ][ 1 ] === 2 ? 'Two Pair' | |
: scoredHistogram[ 0 ][ 1 ] === 2 && scoredHistogram[ 1 ][ 1 ] === 1 ? 'Pair' | |
: `High Card ( ${ scoredHistogram[ 0 ][ 0 ] } )` | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a quick implementation of:
http://nsayer.blogspot.com/2007/07/algorithm-for-evaluating-poker-hands.html