Created
June 8, 2017 19:52
-
-
Save shawa/d969dfebb654a74ebc9eb306e5d7167b to your computer and use it in GitHub Desktop.
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 | |
defp encode([], cur_char, n, cur_encoded), do: "#{cur_encoded}#{n}#{<<cur_char>>}" | |
defp encode([h | tail], cur_char, n, cur_encoded) do | |
case h do | |
^cur_char -> encode tail, h, n + 1, cur_encoded | |
_ -> encode tail, h, 1 , "#{cur_encoded}#{n}#{<<cur_char>>}" | |
end | |
end | |
def encode(string) do | |
[h|tail] = String.to_charlist string | |
encode tail, h, 1, "" | |
end | |
defp decode([], acc), do: acc | |
defp decode([n_char, c | tail], acc) do | |
{n, ""} = Integer.parse <<n_char>> | |
decode tail, (acc <> String.duplicate(<<c>>, n)) | |
end | |
def decode(string) do | |
decode String.to_charlist(string), "" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment