Skip to content

Instantly share code, notes, and snippets.

@davidefiocco
Created June 8, 2017 21:53
Show Gist options
  • Save davidefiocco/f419a09cc024682ee9b9dd547556fa1a to your computer and use it in GitHub Desktop.
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
# 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