Skip to content

Instantly share code, notes, and snippets.

@cassiozen
Last active August 29, 2015 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cassiozen/2e8f18af18021ac68607 to your computer and use it in GitHub Desktop.
Save cassiozen/2e8f18af18021ac68607 to your computer and use it in GitHub Desktop.
Calculates the Rank of a 5 card Poker hand using bit manipulations.
// Calculates the Rank of a 5 card Poker hand using bit manipulations.
// Adapted from the original CPOL-Licensed code by subskybox
// In-depth article explaining how the rank function works available here:
// http://www.codeproject.com/Articles/569271/A-Poker-hand-analyzer-in-JavaScript-using-bit-math
rankPokerHand(hand) {
if(hand.length < 5) return;
let v, i, o, s = 1 << hand[0].rank | 1 << hand[1].rank | 1 << hand[2].rank | 1 << hand[3].rank | 1 << hand[4].rank;
for (i = 0, v = o = 0; i < 5; i++) {
o = Math.pow(2, hand[i].rank * 4);
v += o * ((v / o & 15) + 1);
}
v = v % 15 - ((s / (s & -s) == 31) || (s == 0x403c) ? 3 : 1);
v -= (SUITS[hand[0].suit].value == (SUITS[hand[1].suit].value | SUITS[hand[2].suit].value | SUITS[hand[3].suit].value | SUITS[hand[4].suit].value)) * ((s == 0x7c00) ? -5 : 1);
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment