Skip to content

Instantly share code, notes, and snippets.

@vysakh0
Last active September 4, 2016 08:31
Show Gist options
  • Save vysakh0/609869f6283a2cdc7079 to your computer and use it in GitHub Desktop.
Save vysakh0/609869f6283a2cdc7079 to your computer and use it in GitHub Desktop.
Run length encoding in elixir
defmodule Runlength do
def encode(<< first :: binary-size(1) , rest :: binary>>) do
encode({first, 1}, rest, "")
end
def encode({letter, count}, << letter :: binary-size(1) , rest :: binary>>, result) do
encode({letter, count + 1}, rest, result)
end
def encode({letter, count}, << diff :: binary-size(1) , rest :: binary>>, result) do
result = result <> to_string(count) <> letter
encode({diff, 1}, rest, result)
end
def encode({letter, count}, <<>>, result) do
result <> to_string(count) <> letter
end
end
defmodule RunlengthTest do
use ExUnit.Case
test "run length encoding" do
assert Runlength.encode("AABBBCCCC") == "2A3B4C"
end
end
@andrewshatnyy
Copy link

Oh right I see now. I misread the second definition. Cheers for example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment