Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions solutions/elixir/run-length-encoding/2/lib/run_length_encoder.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
defmodule RunLengthEncoder do
@doc """
Generates a string where consecutive elements are represented as a data value and count.
"AABBBCCCC" => "2A3B4C"
For this example, assume all input are strings, that are all uppercase letters.
It should also be able to reconstruct the data into its original form.
"2A3B4C" => "AABBBCCCC"
"""
@spec encode(String.t()) :: String.t()
def encode(string) do
Regex.replace(~r/(.)\1*/, string, fn
letter, letter -> letter
match, letter -> "#{byte_size(match)}" <> letter
end)
end

@spec decode(String.t()) :: String.t()
def decode(string) do
Regex.replace(~r/([0-9]*)(.)/, string, fn
_, "", letter -> letter
_, count, letter -> String.duplicate(letter, String.to_integer(count))
end)
end
end