Last active
August 29, 2015 14:07
-
-
Save adamrobbie/4e14dba97e59adf2f2c9 to your computer and use it in GitHub Desktop.
Elixir Run-Length Encoding
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 RunLength do | |
def run(string) do | |
compress(String.slice(string, 1..-1), String.slice(string, 0, 1), 1, "") | |
end | |
defp compress("", char, count, result) do | |
result <> Integer.to_string(count) <> char | |
end | |
defp compress(string, char, count, result) do | |
next = String.slice(string, 0, 1) | |
if next == char do | |
compress(String.slice(string, 1..-1), char, count+1, result) | |
else | |
compress( | |
String.slice(string, 1..-1), | |
next, | |
1, | |
result <> Integer.to_string(count) <> char | |
) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment