Skip to content

Instantly share code, notes, and snippets.

@benjamintanweihao
Last active August 1, 2016 20:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benjamintanweihao/7ea8f15a0b6bb7cca26e to your computer and use it in GitHub Desktop.
Save benjamintanweihao/7ea8f15a0b6bb7cca26e to your computer and use it in GitHub Desktop.
Elixir Quiz #2: Run Length Encoding
# Given a string of uppercase characters in the range A-Z,
# replace runs of sequential characters with a single
# instance of that value preceded by the number of items
# in the run.
defmodule RunLengthEncoder do
def encode(string) do
encode_aux(String.codepoints(string), [])
end
def encode_aux([], result) do
result
|> Enum.reverse
|> Enum.map(fn {char, freq} -> "#{freq}#{char}" end)
|> to_string
end
def encode_aux([h1|t1], []) do
encode_aux(t1, [{h1,1}])
end
def encode_aux([h1|t1], [{h1,n}|t2]) do
encode_aux(t1, [{h1,n+1}|t2])
end
def encode_aux([h1|t1], result) do
encode_aux(t1, [{h1,1}|result])
end
end
defmodule RunLengthEncoderTest do
use ExUnit.Case, async: true
test "encoding works with all uppercase" do
input = "JJJTTWPPMMMMYYYYYYYYYVVVVVV"
output = "3J2T1W2P4M9Y6V"
assert RunLengthEncoder.encode(input) == output
end
test "encoding works with all unique letters" do
input = "HORSE"
output = "1H1O1R1S1E"
assert RunLengthEncoder.encode(input) == output
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment