Sha256: 93490f0deb621f3c29e3a4ebda67264fb9d628f5acc4be3ac3752eaa019e295f

Contents?: true

Size: 1.02 KB

Versions: 69

Compression:

Stored size: 1.02 KB

Contents

defmodule RotationalCipher do
  @alphabet "abcdefghijklmnopqrstuvwxyz"
  @alphabet_size String.length(@alphabet)

  for shift <- 0..25 do
    plain = String.split(@alphabet, "", trim: true)

    cipher =
      @alphabet
      |> Kernel.<>(@alphabet)
      |> String.split("", trim: true)
      |> Enum.drop(shift)
      |> Enum.take(@alphabet_size)

    for {p, c} <- Enum.zip(plain, cipher) do
      def translate(unquote(p), unquote(shift)), do: unquote(c)

      def translate(unquote(p |> String.upcase()), unquote(shift)),
        do: unquote(c |> String.upcase())
    end
  end

  # Non a-zA-Z just returns the original character
  def translate(plaintext, _), do: plaintext

  @doc """
  Given a plaintext and amount to shift by, return a rotated string.

  Example:
  iex> RotationalCipher.rotate("Attack at dawn", 13)
  "Nggnpx ng qnja"
  """
  @spec rotate(text :: String.t(), shift :: integer) :: String.t()
  def rotate(text, shift) do
    text
    |> String.split("", trim: true)
    |> Enum.map_join(&translate(&1, shift))
  end
end

Version data entries

69 entries across 69 versions & 1 rubygems

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