Created
April 1, 2018 03:40
-
-
Save EssenceOfChaos/0fa41bf8d03ae21c713f662b8f79228c to your computer and use it in GitHub Desktop.
Maxchars - Given a string, find the character that occurs most frequently.
This file contains 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 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