호두나무 공방/Exercism in Elixir

Atbash Cipher - Exercism in Elixir

2022. 6. 19. 22:52

문제 보기

영문자를 역순으로 뒤집고, 띄어쓰기를 무시하고 5글자 단위로 나누는 기본적인 암-복호화를 구현하는 문제였다. Enum.map/2 안에 들어간 알파벳을 뒤집는 익명 함수는 별도로 분리해서 암-복호화할 때 공통으로 사용할 수도 있었는데, 대문자나 숫자 처리는 암호화 때에만 쓰는 부분이어서 괜히 공통으로 만들었다가 코드가 어려워질 것 같아 다소 중복을 허용하는 형태로 그대로 두었다.

defmodule Atbash do
  @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
    |> String.to_charlist()
    |> Enum.map(fn
      c when c in ?a..?z ->
        ?a + ?z - c
      c when c in ?A..?Z ->
        ?a + ?Z - c
      c when c in ?0..?9 ->
        c
      _ -> nil
    end)
    |> Enum.reject(&is_nil/1)
    |> Enum.chunk_every(5)
    |> Enum.map(&List.to_string/1)
    |> Enum.join(" ")
  end

  @spec decode(String.t()) :: String.t()
  def decode(cipher) do
    cipher
    |> String.replace(" ", "")
    |> String.to_charlist()
    |> Enum.map(fn
      c when c in ?a..?z ->
        ?a + ?z - c
      c -> c
    end)
    |> List.to_string()
  end
end