Skip to content

Instantly share code, notes, and snippets.

@matheusazzi
Last active July 20, 2017 17:12
Show Gist options
  • Save matheusazzi/e0d7d032be9f2ec04e6e9e8156f4be74 to your computer and use it in GitHub Desktop.
Save matheusazzi/e0d7d032be9f2ec04e6e9e8156f4be74 to your computer and use it in GitHub Desktop.
poker.ex
defmodule Poker do
## Rank a poker hand
##
## Card is {:suit, value}, e.g. {:heart, 3}
## Hand is a list of 5 cards
##
## Poker.rank [{:heart, 10}, {:club, 11}, {:heart, 9}, {:diamond, 12}, {:heart, 13}]
## >> :straight
def rank(hand) do
hand
|> Enum.sort(fn({_, n1}, {_, n2}) -> (n1 <= n2) end)
|> rank_hand
end
# Royal Flush
defp rank_hand([{s, 10}, {s, 11}, {s, 12}, {s, 13}, {s, 14}]), do: :royal_flush
# Straight Flush
defp rank_hand([{s, n1}, {s, _}, {s, _}, {s, _}, {s, n2}]) when n2 - n1 == 4, do: :straight_flush
defp rank_hand([{s, 2}, {s, 3}, {s, 4}, {s, 5}, {s, 14}]), do: :straight_flush
# Four of a kind
defp rank_hand([{_, a}, {_, a}, {_, a}, {_, a}, {_, b}]), do: :four_of_a_kind
defp rank_hand([{_, b}, {_, a}, {_, a}, {_, a}, {_, a}]), do: :four_of_a_kind
# Full House
defp rank_hand([{_, a}, {_, a}, {_, a}, {_, b}, {_, b}]), do: :full_house
defp rank_hand([{_, b}, {_, b}, {_, a}, {_, a}, {_, a}]), do: :full_house
# Flush
defp rank_hand([{s, _}, {s, _}, {s, _}, {s, _}, {s, _}]), do: :flush
# Straight
defp rank_hand([{_, n1}, {_, _}, {_, _}, {_, _}, {_, n2}]) when n2 - n1 == 4, do: :straight
defp rank_hand([{_, 2}, {_, 3}, {_, 4}, {_, 5}, {_, 14}]), do: :straight
# Three of a kind
defp rank_hand([{_, a}, {_, a}, {_, a}, {_, _}, {_, _}]), do: :three_of_a_kind
defp rank_hand([{_, _}, {_, a}, {_, a}, {_, a}, {_, _}]), do: :three_of_a_kind
defp rank_hand([{_, _}, {_, _}, {_, a}, {_, a}, {_, a}]), do: :three_of_a_kind
# Two pair
defp rank_hand([{_, a}, {_, a}, {_, b}, {_, b}, {_, _}]), do: :two_pair
defp rank_hand([{_, _}, {_, a}, {_, a}, {_, b}, {_, b}]), do: :two_pair
defp rank_hand([{_, a}, {_, a}, {_, _}, {_, b}, {_, b}]), do: :two_pair
# One pair
defp rank_hand([{_, a}, {_, a}, {_, _}, {_, _}, {_, _}]), do: :one_pair
defp rank_hand([{_, _}, {_, a}, {_, a}, {_, _}, {_, _}]), do: :one_pair
defp rank_hand([{_, _}, {_, _}, {_, a}, {_, a}, {_, _}]), do: :one_pair
defp rank_hand([{_, _}, {_, _}, {_, _}, {_, a}, {_, a}]), do: :one_pair
# High card
defp rank_hand(_), do: :high_card
end
@matheusazzi
Copy link
Author

poker

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment