Last active
June 9, 2017 08:22
-
-
Save brendanmaguire/f62228a00b0d8f33a52840f72f46d945 to your computer and use it in GitHub Desktop.
runlength.ex
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
# | |
# 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