Skip to content

Commit 58dbf7d

Browse files
committed
updated mode(); added hist()
1 parent b5917ba commit 58dbf7d

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed

lib/statistics.ex

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -85,31 +85,28 @@ defmodule Statistics do
8585
"""
8686
@spec mode(list) :: number
8787
def mode([]), do: nil
88-
89-
def mode(list) do
90-
list
91-
|> Enum.map(fn(x) -> {x, 1} end)
92-
|> Enum.reduce(fn(x, acc) -> mode_acc(x, acc) end)
93-
|> Enum.max_by(fn({_, c}) -> c end)
94-
|> mode_val
88+
def mode(list) when is_list(list) do
89+
h = hist(list)
90+
max = Map.values(h) |> Enum.max()
91+
h |> Enum.find(fn {_,val} -> val == max end) |> elem(0)
9592
end
93+
94+
@doc """
95+
Get a frequency count of the values in a list
9696
97-
defp mode_val({val, _}), do: val
98-
99-
defp mode_acc(_, {x, y}) do
100-
%{x => y}
101-
end
97+
## Examples
10298
103-
defp mode_acc({val, _}, acc) do
104-
{_, a} = Map.get_and_update(acc, val, &mode_incr/1)
105-
a
106-
end
99+
iex> Statistics.hist([])
100+
nil
101+
iex> Statistics.hist([1,2,3,2,4,5,2,5,1,2,5,5])
102+
%{1 => 2, 2 => 4, 3 => 1, 4 => 1, 5 => 4}
107103
108-
defp mode_incr(x) do
109-
case x do
110-
nil -> {x, 1}
111-
_ -> {x, x+1}
112-
end
104+
"""
105+
@spec hist(list) :: map
106+
def hist([]), do: nil
107+
def hist(list) when is_list(list) do
108+
list
109+
|> Enum.reduce(%{}, fn(tag, acc) -> Map.update(acc, tag, 1, &(&1 + 1)) end)
113110
end
114111

115112
@doc """

0 commit comments

Comments
 (0)