Skip to content

Instantly share code, notes, and snippets.

@EssenceOfChaos
Created April 1, 2018 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EssenceOfChaos/0fa41bf8d03ae21c713f662b8f79228c to your computer and use it in GitHub Desktop.
Save EssenceOfChaos/0fa41bf8d03ae21c713f662b8f79228c to your computer and use it in GitHub Desktop.
Maxchars - Given a string, find the character that occurs most frequently.
defmodule Maxchar do
@moduledoc """
Given a string, return the character that occurs most frequently
"""
def main(str) when is_binary(str) do
str
|> count_chars()
|> print()
end
defp count_chars(string) do
count_chars(String.graphemes(string), Map.new())
end
defp count_chars([], map), do: map
defp count_chars([first | rest], map) do
case Map.has_key?(map, first) do
true ->
map = Map.update!(map, first, fn val -> val + 1 end)
count_chars(rest, map)
false ->
map = Map.put_new(map, first, 1)
count_chars(rest, map)
end
end
defp print(map) do
map
|> Enum.max_by(fn {char, value} -> value end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment