Skip to content

Instantly share code, notes, and snippets.

@rickhull
Created December 22, 2014 03:22
Show Gist options
  • Save rickhull/3779263e89c4c84ad9bd to your computer and use it in GitHub Desktop.
Save rickhull/3779263e89c4c84ad9bd to your computer and use it in GitHub Desktop.
given a list of items (with repeats), which one has the highest frequency?
defp majority(list) do
largest = 0
maj = []
list |> Enum.group_by(&(&1)) |> Enum.each(fn {val,lst} ->
case length(list) do
cnt when cnt > largest ->
largest = cnt
maj = [val]
cnt when cnt == largest ->
maj = [val | maj]
end
end)
Enum.sample(maj)
end
@chrismccord
Copy link

defmodule Find do
  def max_occurrence([head | tail]) do
    tail
    |> Enum.reduce({head, Dict.put(%{}, head, 1)}, fn i, {lead, group} ->
      i_count = Dict.get(group, i, 0) + 1
      if i_count > Dict.get(group, lead) do
        {i, Dict.put(group, i, i_count)}
      else
        {lead, Dict.put(group, i, i_count)}
      end
    end)
    |> elem(0)
  end
end

# iex(35)> Find.max_occurrence([10, 1, 1, 2, 1, 2, 8])
#1

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