Forked from benjamintanweihao/run_length_encoder.ex
Created
October 25, 2015 05:45
-
-
Save loganhasson/1a661ead437d56e0f136 to your computer and use it in GitHub Desktop.
Elixir Quiz #2: Run Length Encoding
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
# 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