Skip to content

Instantly share code, notes, and snippets.

@brendanmaguire
Last active June 9, 2017 08:22
Show Gist options
  • Save brendanmaguire/f62228a00b0d8f33a52840f72f46d945 to your computer and use it in GitHub Desktop.
Save brendanmaguire/f62228a00b0d8f33a52840f72f46d945 to your computer and use it in GitHub Desktop.
runlength.ex
#
# A solution to the problem defined at https://github.com/marjaimate/runlength/
#
defmodule Runlength do
def encode(string) do
String.codepoints(string)
|> Enum.reverse
|> Enum.reduce([], &char_to_tuples/2)
|> Enum.reduce("", fn ({char, count}, acc) -> "#{acc}#{Integer.to_string(count)}#{char}" end)
end
def char_to_tuples(char, []) do
[{char, 1}]
end
def char_to_tuples(char, [{char, count} | t]) do
[{char, count + 1} | t]
end
def char_to_tuples(char, acc) do
[{char, 1} | acc]
end
def decode(string) do
string = String.codepoints(string)
expand(string, "")
end
def expand([], acc) do acc end
def expand([count_str | [char | tail]], acc) do
{count, _} = Integer.parse(count_str)
next = String.duplicate(char, count)
expand(tail, "#{acc}#{next}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment