Skip to content

Instantly share code, notes, and snippets.

@vysakh0
Last active February 11, 2016 05:17
Show Gist options
  • Save vysakh0/c791660db9600a637f35 to your computer and use it in GitHub Desktop.
Save vysakh0/c791660db9600a637f35 to your computer and use it in GitHub Desktop.
Find the most frequent(continuously repeated) integer in a list.
defmodule Frequent do
def number( [num | tail] ) do
number({num, 1}, tail, {num, 1})
end
def number({num, count}, [ num | tail ], max) do
number({num, count + 1}, tail, max)
end
def number({_num, count} = current, [ diff | tail ], {_, max_count} = max) do
if count > max_count do
max = current
end
number({diff, 1}, tail, max)
end
def number(_, [], max), do: max
end
defmodule FrequentTest do
use ExUnit.Case
test "most frequent number" do
assert Frequent.number([1, 1, 2, 2, 2, 3, 3]) == {2, 3}
assert Frequent.number([1, 1, 1, 1, 2, 2, 2, 3, 3]) == {1, 4}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment