Created
June 9, 2017 07:56
-
-
Save ciaranfinn/dc1f17cc9923b13d4df2bd4b2dc5ae84 to your computer and use it in GitHub Desktop.
Elixir - Run-length (Encode/Decode)
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 encode(""), do: "" | |
def encode(<<head :: binary-size(1), tail :: binary>>) do | |
do_encode("", head, tail) | |
end | |
defp do_encode(result, acc = <<head :: binary-size(1), _ :: binary>>, "") do | |
result <> Integer.to_string(String.length(acc)) <> head | |
end | |
defp do_encode(result, | |
acc = <<head_1 :: binary-size(1), rest_1 :: binary>>, | |
<<head_2 :: binary-size(1), rest_2 :: binary >>) do | |
if head_1 == head_2 do | |
do_encode(result, head_1 <> rest_1 <> head_2, rest_2) | |
else | |
do_encode( | |
result <> Integer.to_string(String.length(acc)) <> head_1, | |
head_2, | |
rest_2 | |
) | |
end | |
end | |
def decode(<<length :: binary-size(1), character :: binary-size(1), rest :: binary>>) do | |
do_decode("", {length, character}, rest) | |
end | |
defp do_decode(acc, {length, character}, "") do | |
acc <> String.duplicate(character, String.to_integer(length)) | |
end | |
defp do_decode(acc, | |
{length, character}, | |
<<length2 :: binary-size(1), | |
character2 :: binary-size(1), | |
rest :: binary>>) do | |
do_decode(acc <> String.duplicate(character, String.to_integer(length)), {length2, character2}, rest) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment