From 0849c576fd9f0bc420709979edc24f62ca8efad7 Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Wed, 6 Aug 2025 12:27:42 +0000 Subject: [PATCH] [Sync Iteration] elixir/run-length-encoding/1 --- .../1/lib/run_length_encoder.ex | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 solutions/elixir/run-length-encoding/1/lib/run_length_encoder.ex diff --git a/solutions/elixir/run-length-encoding/1/lib/run_length_encoder.ex b/solutions/elixir/run-length-encoding/1/lib/run_length_encoder.ex new file mode 100644 index 0000000..d250db7 --- /dev/null +++ b/solutions/elixir/run-length-encoding/1/lib/run_length_encoder.ex @@ -0,0 +1,26 @@ +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.scan(~r/(.)\1*/, string) + |> Enum.map_join(fn + [letter, letter] -> letter + [match, letter] -> "#{byte_size(match)}" <> letter + end) + end + + @spec decode(String.t()) :: String.t() + def decode(string) do + Regex.scan(~r/([0-9]*)(.)/, string) + |> Enum.map_join(fn + [_, "", letter] -> letter + [_, count, letter] -> String.duplicate(letter, String.to_integer(count)) + end) + end +end