Skip to content

Instantly share code, notes, and snippets.

@ryanwinchester
Last active May 15, 2018 21:50
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 ryanwinchester/4ca8e26821971fd59f40de677a11fcd7 to your computer and use it in GitHub Desktop.
Save ryanwinchester/4ca8e26821971fd59f40de677a11fcd7 to your computer and use it in GitHub Desktop.
Just having fun...
defmodule Poker do
@deck ~w(
A♣ 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣
A◆ 2◆ 3◆ 4◆ 5◆ 6◆ 7◆ 8◆ 9◆ 10◆ J◆ Q◆ K◆
A♠ 2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠
A♥ 2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥
)
def deck, do: Enum.with_index(@deck)
def deal(hand_count \\ 1) do
deck()
|> Enum.shuffle()
|> Enum.chunk_every(5)
|> Enum.take(hand_count)
end
def straight?(hand) do
hand
|> Enum.map(&(elem(&1, 1) |> rem(13)))
|> Enum.sort()
|> Enum.reduce(fn
x, {n, seq?} -> {x, seq? && x == n + 1}
x, n -> {x, x == n + 1}
end)
|> elem(1)
end
def flush?(hand) do
hand
|> Enum.map(&(elem(&1, 0) |> String.last()))
|> Enum.uniq()
|> (&(Enum.count(&1) === 1)).()
end
def straight_flush?(hand), do: straight?(hand) and flush?(hand)
end
@ryanwinchester
Copy link
Author

ryanwinchester commented May 15, 2018

Check it:

# Check Random
random_hand = Poker.deal_hand()
IO.inspect(random_hand)
IO.puts("straight? #{Poker.straight?(random_hand)}")
IO.puts("flush? #{Poker.flush?(random_hand)}")
IO.puts("")

# Check Straight
straight_hand = [{"A♠", 26}, {"2◆", 14}, {"3♣", 2}, {"4♥", 42}, {"5♣", 4}]
IO.inspect(straight_hand)
IO.puts("straight? #{Poker.straight?(straight_hand)}")
IO.puts("flush? #{Poker.flush?(straight_hand)}")
IO.puts("")

# Check Flush
flush_hand = [{"3♣", 2}, {"4♣", 3}, {"A♣", 0}, {"6♣", 5}, {"7♣", 6}]
IO.inspect(flush_hand)
IO.puts("straight? #{Poker.straight?(flush_hand)}")
IO.puts("flush? #{Poker.flush?(flush_hand)}")
IO.puts("")

# Check Straight Flush
straight_flush_hand = [{"3♣", 2}, {"4♣", 3}, {"5♣", 4}, {"6♣", 5}, {"7♣", 6}]
IO.inspect(straight_flush_hand)
IO.puts("straight? #{Poker.straight?(straight_flush_hand)}")
IO.puts("flush? #{Poker.flush?(straight_flush_hand)}")

Output:

[{"5♥", 43}, {"7♣", 6}, {"2◆", 14}, {"K♠", 38}, {"10♣", 9}]
straight? false
flush? false

[{"A♠", 26}, {"2◆", 14}, {"3♣", 2}, {"4♥", 42}, {"5♣", 4}]
straight? true
flush? false

[{"3♣", 2}, {"4♣", 3}, {"A♣", 0}, {"6♣", 5}, {"7♣", 6}]
straight? false
flush? true

[{"3♣", 2}, {"4♣", 3}, {"5♣", 4}, {"6♣", 5}, {"7♣", 6}]
straight? true
flush? true

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