Sha256: ca6f327e4047569543c9af6ce72612eba7a23cef1f67c06ed89b84575e55689f

Contents?: true

Size: 855 Bytes

Versions: 131

Compression:

Stored size: 855 Bytes

Contents

defmodule Atbash do
  @key Enum.zip(?a..?z, ?z..?a) |> Enum.into(%{})

  @doc """
  Encode a given plaintext to the corresponding ciphertext

  ## Examples

  iex> Atbash.encode("completely insecure")
  "xlnko vgvob rmhvx fiv"
  """
  @spec encode(String.t()) :: String.t()
  def encode(plaintext) do
    plaintext |> normalize |> transpose |> chunk |> Enum.join(" ")
  end

  @spec decode(String.t()) :: String.t()
  def decode(cipher) do
    cipher |> normalize |> transpose
  end

  defp normalize(input) do
    Regex.replace(~r{\W}, String.downcase(input), "")
  end

  defp transpose(text) do
    text
    |> String.to_charlist()
    |> Enum.map(&convert/1)
    |> List.to_string()
  end

  defp convert(character) do
    Map.get(@key, character, character)
  end

  defp chunk(input) do
    Regex.scan(~r(.{1,5}), input) |> List.flatten()
  end
end

Version data entries

131 entries across 131 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/atbash-cipher/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/atbash-cipher/example.exs