Created
September 23, 2015 18:27
-
-
Save KamilLelonek/7bbe1ccd486b7d54b262 to your computer and use it in GitHub Desktop.
An example implementaion on Yatzy game during Copenhagen Elixir Meetup
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
defmodule Yatzy.Score do | |
def upper(n, ds), do: n * count(n, ds) | |
defp count(n, ls), do: select_elements(n, ls) |> Enum.count | |
defp select_elements(n, ls), do: ls |> Enum.filter &(&1 == n) | |
def chance(ds), do: ds |> Enum.reduce &(&1 + &2) | |
def yatzy(ds) do | |
case count_unique_elements(ds) do | |
1 -> 50 | |
_ -> 0 | |
end | |
end | |
defp count_unique_elements(ds), do: ds |> Enum.uniq |> Enum.count | |
def small_straight(ds) do | |
return_if_matches(ds, [1, 2, 3, 4, 5], 15) | |
end | |
def large_straight(ds) do | |
return_if_matches(ds, [2, 3, 4, 5, 6], 20) | |
end | |
defp return_if_matches(collection, pattern, value) do | |
cond do | |
Enum.sort(collection) == pattern -> value | |
:true -> 0 | |
end | |
end | |
def four_of_a_kind(ds) do | |
case Enum.sort(ds) do | |
[_, x, x, x, x] -> 4 * x | |
[x, x, x, x, _] -> 4 * x | |
_ -> 0 | |
end | |
end | |
def three_of_a_kind(ds) do | |
ds | |
|> group_by_identity | |
|> filter_elements_with_occurence_of_3 | |
|> map_to_values | |
|> List.flatten | |
|> sum_all_elements | |
end | |
defp group_by_identity(collection), | |
do: collection |> Enum.group_by(&(&1)) | |
defp filter_elements_with_occurence_of_3(collection), | |
do: collection |> Enum.filter(&has_size_of_3/1) | |
defp has_size_of_3({k, v}), do: Enum.count(v) == 3 | |
defp map_to_values(collection), | |
do: collection |> Enum.map(fn {k,v} -> v end) | |
defp sum_all_elements(collection), | |
do: collection |> Enum.reduce(0, &(&1 + &2)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment