호두나무 공방/Exercism in Elixir

Rotational Cipher - Exercism in Elixir

2022. 6. 8. 22:27

문제 보기

카이사르 암호(영문자를 주어진 거리만큼 밀어서 다른 문자로 변환하는 식으로 암호화하는 방식)를 구현하는 문제였다. 이런 경우에는 문자가 영문자 범위를 넘어가는지 아닌지 확인해야 하므로 문자 리스트로 처리하는 것이 자연스럽다. convert 함수가 약간 중언부언하는 느낌이 있는데 rem을 쓰는 것보다는 코드를 읽기에 이쪽이 조금 더 나은 것 같아 그대로 두었다.

defmodule RotationalCipher do
  @spec rotate(text :: String.t(), shift :: integer) :: String.t()
  def rotate(text, shift) do
    text
    |> String.to_charlist()
    |> Enum.map(&convert(&1, shift))
    |> List.to_string()
  end

  defp convert(c, shift) when c in ?A..?Z do
    if c + shift > ?Z, do: c + shift - 26, else: c + shift
  end
  defp convert(c, shift) when c in ?a..?z do
    if c + shift > ?z, do: c + shift - 26, else: c + shift
  end
  defp convert(c, _shift), do: c
end