Skip to content

Instantly share code, notes, and snippets.

@dwarring
Forked from masak/poker hand classification
Last active August 29, 2015 14:02
Show Gist options
  • Save dwarring/4472a8da9dfcd963a8c0 to your computer and use it in GitHub Desktop.
Save dwarring/4472a8da9dfcd963a8c0 to your computer and use it in GitHub Desktop.
# courtesy of https://gist.github.com/masak/244255
use v6;
enum Suit < ♥ ♦ ♣ ♠ >;
enum Rank (2, 3, 4, 5, 6, 7, 8, 9, 10,
'j', 'q', 'k', 'a');
class Card {
has Suit $.suit;
has Rank $.rank;
method Str {
$.rank.name ~ ' of ' ~ $.suit.name;
}
}
subset PokerHand of List where { .elems == 5 && all(|$_) ~~ Card }
sub n-of-a-kind($n, @cards) {
for @cards>>.rank.uniq -> $rank {
return True if $n == grep $rank, @cards>>.rank;
}
return False;
}
subset Quad of PokerHand where { n-of-a-kind(4, $_) }
subset ThreeOfAKind of PokerHand where { n-of-a-kind(3, $_) }
subset OnePair of PokerHand where { n-of-a-kind(2, $_) }
subset FullHouse of PokerHand where OnePair & ThreeOfAKind;
subset Flush of PokerHand where -> @cards { [==] @cards>>.suit }
subset Straight of PokerHand where sub (@cards) {
my @sorted-cards = @cards.sort({ .rank });
my ($head, @tail) = @sorted-cards;
for @tail -> $card {
return False if $card.rank != $head.rank + 1;
$head = $card;
}
return True;
}
subset StraightFlush of Flush where Straight;
subset TwoPair of PokerHand where sub (@cards) {
my $pairs = 0;
for @cards>>.rank.uniq -> $rank {
++$pairs if 2 == grep $rank, @cards>>.rank;
}
return $pairs == 2;
}
sub classify(PokerHand $_) {
when StraightFlush { 'straight flush', 8 }
when Quad { 'four of a kind', 7 }
when FullHouse { 'full house', 6 }
when Flush { 'flush', 5 }
when Straight { 'straight', 4 }
when ThreeOfAKind { 'three of a kind', 3 }
when TwoPair { 'two pair', 2 }
when OnePair { 'one pair', 1 }
when * { 'high cards', 0 }
}
# ... parsing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment