Skip to content

Instantly share code, notes, and snippets.

@shawa
Created June 8, 2017 19:52
Show Gist options
  • Save shawa/d969dfebb654a74ebc9eb306e5d7167b to your computer and use it in GitHub Desktop.
Save shawa/d969dfebb654a74ebc9eb306e5d7167b to your computer and use it in GitHub Desktop.
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