Skip to content

Instantly share code, notes, and snippets.

@adamrobbie
Last active August 29, 2015 14:07
Show Gist options
  • Save adamrobbie/4e14dba97e59adf2f2c9 to your computer and use it in GitHub Desktop.
Save adamrobbie/4e14dba97e59adf2f2c9 to your computer and use it in GitHub Desktop.
Elixir Run-Length Encoding
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