Skip to content

Poker

Pick the best hand, or the hands that tie for best, from a list of five-card poker hands.

Adapted from Exercism’s problem specification (MIT). Listed under Games & Simulation.

// FILE: poker.nomi
//# Picks the best poker hands from a list of hands.

/// Why a hand cannot be scored.
pub enum Error
    InvalidHand String
end

/// The hands of poker, weakest first, so the derived order ranks them.
enum Category
    HighCard
    OnePair
    TwoPair
    ThreeOfAKind
    Straight
    Flush
    FullHouse
    FourOfAKind
    StraightFlush
end

derive Comparable for Category

/// How strong a hand is: its category, then the ranks that break a tie
/// within it, in the order they are compared. The derived order compares
/// the fields in the order they are declared.
struct Score
    category: Category
    ranks:    List<Int>
end

derive Comparable for Score

struct Card
    rank: Int
    suit: String
end

/// The hands of `hands` that score highest, in the order given: one, or
/// every hand that ties for best.
pub fn best_hands(hands: List<String>) -> Result<List<String>, Error>
    scored =
        hands
        |> Iter.map(fn hand -> Ok((hand, score(hand)?)))
        |> Result.collect()?

    Some(best) = scored |> Iter.map(.second) |> Iter.max() else return Ok([])

    scored
    |> Iter.filter(fn (_hand, score) -> score == best)
    |> Iter.map(.first)
    |> Iter.to_list()
    |> Ok()
end

/// The score of a hand of five cards written as `"4S 5S 7H 8D JC"`.
fn score(hand: String) -> Result<Score, Error>
    Some(cards) = hand |> String.words() |> Iter.map(card) |> Maybe.collect() else
        return Err(.InvalidHand(hand))
    end

    if Iter.count(cards) != 5 then return Err(.InvalidHand(hand))

    // Each rank with how many cards show it, the largest group first and
    // the higher rank first among groups of one size.
    groups =
        cards
        |> Iter.map(.rank)
        |> Iter.frequencies()
        |> Iter.sort_by(.Descending, fn (rank, count) -> (count, rank))

    counts = groups |> Iter.map(.second) |> Iter.to_list()
    ranks = groups |> Iter.map(.first) |> Iter.to_list()
    flush = cards |> Iter.map(.suit) |> Iter.to_set() |> Set.size() == 1

    Ok(
        case (counts, straight(ranks), flush)
            ([4, 1], _, _)         -> {category: .FourOfAKind, ranks:}
            ([3, 2], _, _)         -> {category: .FullHouse, ranks:}
            ([3, 1, 1], _, _)      -> {category: .ThreeOfAKind, ranks:}
            ([2, 2, 1], _, _)      -> {category: .TwoPair, ranks:}
            ([2, 1, 1, 1], _, _)   -> {category: .OnePair, ranks:}
            (_, Some(high), True)  -> {category: .StraightFlush, ranks: high}
            (_, Some(high), False) -> {category: .Straight, ranks: high}
            (_, None, True)        -> {category: .Flush, ranks:}
            (_, None, False)       -> {category: .HighCard, ranks:}
        end
    )
end

/// The ranks of a straight, highest first, when `ranks` (five different
/// ones, highest first) make one. An ace counts low in `A 2 3 4 5`.
fn straight(ranks: List<Int>) -> Maybe<List<Int>>
    case ranks
        [14, 5, 4, 3, 2] -> Some([5, 4, 3, 2, 1])
        [high, _, _, _, low] when high - low == 4 -> Some(ranks)
        _ -> None
    end
end

/// A card written as its rank and its suit, `"10H"` or `"QS"`.
fn card(text: String) -> Maybe<Card>
    length = String.length(text)
    suit = String.drop(text, length - 1)

    if not suit in ["S", "H", "D", "C"] then return None

    rank = case String.take(text, length - 1)
        "J"    -> Some(11)
        "Q"    -> Some(12)
        "K"    -> Some(13)
        "A"    -> Some(14)
        digits -> pip_rank(digits)
    end

    Some(Card{rank: rank?, suit:})
end

/// The rank of a numbered card, 2 to 10.
fn pip_rank(digits: String) -> Maybe<Int>
    n = String.to_int(digits)?

    if n in 2..=10 then Some(n) else None
end

// FILE: poker_test.nomi
import poker

test "best hands"
    [
        ("single hand always wins", ["4S 5S 7H 8D JC"], ["4S 5S 7H 8D JC"]),
        (
            "highest card out of all hands wins",
            ["4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH"],
            ["3S 4S 5D 6H JH"],
        ),
        (
            "a tie has multiple winners",
            ["4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH", "3H 4H 5C 6C JD"],
            ["3S 4S 5D 6H JH", "3H 4H 5C 6C JD"],
        ),
        (
            "multiple hands with the same high cards, tie compares next highest ranked, down to last card",
            ["3S 5H 6S 8D 7H", "2S 5D 6D 8C 7S"],
            ["3S 5H 6S 8D 7H"],
        ),
        (
            "winning high card hand also has the lowest card",
            ["2S 5H 6S 8D 7H", "3S 4D 6D 8C 7S"],
            ["2S 5H 6S 8D 7H"],
        ),
        ("one pair beats high card", ["4S 5H 6C 8D KH", "2S 4H 6S 4D JH"], ["2S 4H 6S 4D JH"]),
        ("highest pair wins",        ["4S 2H 6S 2D JH", "2S 4H 6C 4D JD"], ["2S 4H 6C 4D JD"]),
        (
            "both hands have the same pair, high card wins",
            ["4H 4S AH JC 3D", "4C 4D AS 5D 6C"],
            ["4H 4S AH JC 3D"],
        ),
        ("two pairs beats one pair", ["2S 8H 6S 8D JH", "4S 5H 4C 8C 5C"], ["4S 5H 4C 8C 5C"]),
        (
            "both hands have two pairs, highest ranked pair wins",
            ["2S 8H 2D 8D 3H", "4S 5H 4C 8S 5D"],
            ["2S 8H 2D 8D 3H"],
        ),
        (
            "both hands have two pairs, with the same highest ranked pair, tie goes to low pair",
            ["2S QS 2C QD JH", "JD QH JS 8D QC"],
            ["JD QH JS 8D QC"],
        ),
        (
            "both hands have two identically ranked pairs, tie goes to remaining card (kicker)",
            ["JD QH JS 8D QC", "JS QS JC 2D QD"],
            ["JD QH JS 8D QC"],
        ),
        (
            "both hands have two pairs that add to the same value, win goes to highest pair",
            ["6S 6H 3S 3H AS", "7H 7S 2H 2S AC"],
            ["7H 7S 2H 2S AC"],
        ),
        (
            "two pairs first ranked by largest pair",
            ["5C 2S 5S 4H 4C", "6S 2S 6H 7C 2C"],
            ["6S 2S 6H 7C 2C"],
        ),
        (
            "three of a kind beats two pair",
            ["2S 8H 2H 8D JH", "4S 5H 4C 8S 4H"],
            ["4S 5H 4C 8S 4H"],
        ),
        (
            "both hands have three of a kind, tie goes to highest ranked triplet",
            ["2S 2H 2C 8D JH", "4S AH AS 8C AD"],
            ["4S AH AS 8C AD"],
        ),
        (
            "with multiple decks, two players can have same three of a kind, ties go to highest remaining cards",
            ["5S AH AS 7C AD", "4S AH AS 8C AD"],
            ["4S AH AS 8C AD"],
        ),
        (
            "a straight beats three of a kind",
            ["4S 5H 4C 8D 4H", "3S 4D 2S 6D 5C"],
            ["3S 4D 2S 6D 5C"],
        ),
        (
            "aces can end a straight (10 J Q K A)",
            ["4S 5H 4C 8D 4H", "10D JH QS KD AC"],
            ["10D JH QS KD AC"],
        ),
        (
            "aces can start a straight (A 2 3 4 5)",
            ["4S 5H 4C 8D 4H", "4D AH 3S 2D 5C"],
            ["4D AH 3S 2D 5C"],
        ),
        (
            "aces cannot be in the middle of a straight (Q K A 2 3)",
            ["2C 3D 7H 5H 2S", "QS KH AC 2D 3S"],
            ["2C 3D 7H 5H 2S"],
        ),
        (
            "both hands with a straight, tie goes to highest ranked card",
            ["4S 6C 7S 8D 5H", "5S 7H 8S 9D 6H"],
            ["5S 7H 8S 9D 6H"],
        ),
        (
            "even though an ace is usually high, a 5-high straight is the lowest-scoring straight",
            ["2H 3C 4D 5D 6H", "4S AH 3S 2D 5H"],
            ["2H 3C 4D 5D 6H"],
        ),
        ("flush beats a straight", ["4C 6H 7D 8D 5H", "2S 4S 5S 6S 7S"], ["2S 4S 5S 6S 7S"]),
        (
            "both hands have a flush, tie goes to high card, down to the last one if necessary",
            ["2H 7H 8H 9H 6H", "3S 5S 6S 7S 8S"],
            ["2H 7H 8H 9H 6H"],
        ),
        ("full house beats a flush", ["3H 6H 7H 8H 5H", "4S 5H 4C 5D 4H"], ["4S 5H 4C 5D 4H"]),
        (
            "both hands have a full house, tie goes to highest-ranked triplet",
            ["4H 4S 4D 9S 9D", "5H 5S 5D 8S 8D"],
            ["5H 5S 5D 8S 8D"],
        ),
        (
            "with multiple decks, both hands have a full house with the same triplet, tie goes to the pair",
            ["5H 5S 5D 9S 9D", "5H 5S 5D 8S 8D"],
            ["5H 5S 5D 9S 9D"],
        ),
        (
            "four of a kind beats a full house",
            ["4S 5H 4D 5D 4H", "3S 3H 2S 3D 3C"],
            ["3S 3H 2S 3D 3C"],
        ),
        (
            "both hands have four of a kind, tie goes to high quad",
            ["2S 2H 2C 8D 2D", "4S 5H 5S 5D 5C"],
            ["4S 5H 5S 5D 5C"],
        ),
        (
            "with multiple decks, both hands with identical four of a kind, tie determined by kicker",
            ["3S 3H 2S 3D 3C", "3S 3H 4S 3D 3C"],
            ["3S 3H 4S 3D 3C"],
        ),
        (
            "straight flush beats four of a kind",
            ["4S 5H 5S 5D 5C", "7S 8S 9S 6S 10S"],
            ["7S 8S 9S 6S 10S"],
        ),
        (
            "aces can end a straight flush (10 J Q K A)",
            ["KC AH AS AD AC", "10C JC QC KC AC"],
            ["10C JC QC KC AC"],
        ),
        (
            "aces can start a straight flush (A 2 3 4 5)",
            ["KS AH AS AD AC", "4H AH 3H 2H 5H"],
            ["4H AH 3H 2H 5H"],
        ),
        (
            "aces cannot be in the middle of a straight flush (Q K A 2 3)",
            ["2C AC QC 10C KC", "QH KH AH 2H 3H"],
            ["2C AC QC 10C KC"],
        ),
        (
            "both hands have a straight flush, tie goes to highest-ranked card",
            ["4H 6H 7H 8H 5H", "5S 7S 8S 9S 6S"],
            ["5S 7S 8S 9S 6S"],
        ),
        (
            "even though an ace is usually high, a 5-high straight flush is the lowest-scoring straight flush",
            ["2H 3H 4H 5H 6H", "4D AD 3D 2D 5D"],
            ["2H 3H 4H 5H 6H"],
        ),
    ]
    |> subtests (description, hands, expected), description
        assert poker.best_hands(hands) == Ok(expected)
    end
end

// Not a canonical case: the canonical hands are all well formed.
test "a hand with a card that is not a card is refused"
    assert poker.best_hands(["4S 5S 7H 8D 1C"]) == Err(.InvalidHand("4S 5S 7H 8D 1C"))
    assert poker.best_hands(["4S 5S 7H 8D JX"]) == Err(.InvalidHand("4S 5S 7H 8D JX"))
    assert poker.best_hands(["4S 5S 7H 8D"]) == Err(.InvalidHand("4S 5S 7H 8D"))
end
  • Each hand gets a Score: its Category, an enum of the nine hands from high card to straight flush, and the ranks that break a tie, in the order they are compared. Both derive Comparable, so the enum’s declaration order ranks the categories and the struct compares category first, then the rank lists lexicographically. The best hands are those whose score equals Iter.max of the scores, kept in input order.
  • The tie-break ranks come from one sort: each rank with how many cards show it, sorted descending by (count, rank). A full house 5 5 5 9 9 gives [5, 9], two pairs J Q J Q 8 give [12, 11, 8], and a high-card hand its five ranks from the top, so every category compares its ranks the same way.
  • The category is one case over the group counts, the straight and the flush together: ([3, 2], _, _) is a full house, (_, Some(high), True) a straight flush. straight answers the straight’s ranks, [5, 4, 3, 2, 1] for the wheel A 2 3 4 5, so a 5-high straight ranks below a 6-high one without a case of its own.
  • The hands arrive as text, so a card that is not a card is data from outside: best_hands returns Err(.InvalidHand(hand)) for it, or for a hand that is not five cards, rather than trapping. The canonical data has no such hand; the test file adds one test of three, marked as not canonical.
  • The 37 current canonical cases are one subtests table named by the description column. Two cases that newer ones reimplement are left out: the first “two players can have same three of a kind” case and the first “both hands have a flush” case, whose newer versions use different hands.