Created
June 8, 2017 21:53
-
-
Save davidefiocco/f419a09cc024682ee9b9dd547556fa1a to your computer and use it in GitHub Desktop.
Conor, Fernando, Davide' s solution for run length encoder/decoder at github.com/marjaimate/runlength
This file contains hidden or 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
# Conor, Fernando, Davide + wisdom of the crowd solution for | |
# https://github.com/marjaimate/runlength | |
defmodule Runlength do | |
def encode(string) do | |
encode(string, "") | |
end | |
def encode("", acc) do | |
acc | |
end | |
def encode(<<char :: binary-size(1), tail :: binary>> = whole_thing, acc) do | |
remaining = String.trim_leading(whole_thing, char) | |
occurrences = String.length(whole_thing) - String.length(remaining) | |
encode(remaining, acc <> Integer.to_string(occurrences) <> char) | |
end | |
def decode(string) do | |
decode(string, "") | |
end | |
def decode("", acc), do: acc | |
def decode(string, acc) do | |
{occurrences, rest} = Integer.parse(string) | |
<<char :: binary-size(1), remaining :: binary>> = rest | |
decode(remaining, acc <> String.duplicate(char, occurrences)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment