Last active
August 29, 2015 14:20
-
-
Save tallakt/97a79c3e1bd9289a2660 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A hand is a list of five with tuples {rank, color} | |
defmodule Hand do | |
@ranks 2..10 |> Enum.concat([:j, :q, :k, :a]) | |
@consecutive_ranks (@ranks | |
|> Stream.cycle | |
|> Stream.chunk(2,1) | |
|> Enum.take(13)) | |
@rank_weight (@ranks | |
|> Enum.with_index | |
|> Enum.map(fn {x, i} -> {i, x} end) | |
|> Enum.into(Map.new)) | |
def sort_by_rank(hand) do | |
rw = @rank_weight | |
hand | |
|> Enum.sort_by fn {r, _} -> Dict.get(rw, r) end | |
end | |
def straight?(hand) do | |
hand | |
|> sort_by_rank | |
|> Enum.chunk(2, 1) | |
|> Enum.all?(fn | |
[{r1, _}, {r2, _}] when [r1, r2] in @consecutive_ranks -> | |
true | |
_ -> | |
false | |
end) | |
end | |
def straight_flush?(hand) do | |
hand | |
|> sort_by_rank | |
|> Enum.chunk(2, 1) | |
|> Enum.all?(fn | |
[{r1, c}, {r2, c}] when [r1, r2] in @consecutive_ranks -> | |
true | |
_ -> | |
false | |
end) | |
end | |
def kind_of_four?([{r, _}, {r, _}, {r, _}, {r, _}, _ ]), do: true | |
def kind_of_four?([{r, _}, {r, _}, {r, _}, _, {r, _}]), do: true | |
def kind_of_four?([{r, _}, {r, _}, _, {r, _}, {r, _}]), do: true | |
def kind_of_four?([{r, _}, _, {r, _}, {r, _}, {r, _}]), do: true | |
def kind_of_four?([_, {r, _}, {r, _}, {r, _}, {r, _}]), do: true | |
def kind_of_four?(_), do: false | |
end | |
flush_hand = for {r, c} <- (5..10 |> Enum.zip([:s, :s, :d, :h, :h])), do: {r, c} | |
kind_of_four_hand = (for color <- [:s, :d, :h, :c], do: {:a, color}) ++ [{:q, :d}] | |
for hand <- [flush_hand, kind_of_four_hand] do | |
shuffled = hand |> Enum.shuffle # make sure sort works | |
IO.puts "Hand: #{shuffled |> inspect}" | |
IO.puts "Straight flush: #{shuffled |> Hand.straight_flush?}" | |
IO.puts "Flush: #{shuffled |> Hand.straight?}" | |
IO.puts "Kind of four: #{shuffled |> Hand.kind_of_four?}" | |
IO.puts "" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment