Created
July 22, 2021 13:05
-
-
Save aschiavon91/af3fa090eb8f11358d8b0127b25c3372 to your computer and use it in GitHub Desktop.
ROT in elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule RotationalCipher do | |
| @doc """ | |
| Given a plaintext and amount to shift by, return a rotated string. | |
| Example: | |
| iex> RotationalCipher.rotate("Attack at dawn", 13) | |
| "Nggnpx ng qnja" | |
| """ | |
| @lower_start ?a | |
| @lower_end ?z | |
| @upper_start ?A | |
| @upper_end ?Z | |
| @lower_range @lower_start..@lower_end | |
| @upper_range @upper_start..@upper_end | |
| @letters_in_alphabet 26 | |
| @spec rotate(text :: String.t(), shift :: integer) :: String.t() | |
| def rotate(text, shift) do | |
| text | |
| |> String.to_charlist() | |
| |> Enum.map(&do_rotate(&1, shift)) | |
| |> to_string() | |
| end | |
| defp do_rotate(char, shift) when char in @lower_range and shift >= 0, | |
| do: rem(char - @lower_start + shift, @letters_in_alphabet) + @lower_start | |
| defp do_rotate(char, shift) when char in @lower_range and shift < 0, | |
| do: rem(char - @lower_end + shift, @letters_in_alphabet) + @lower_end | |
| defp do_rotate(char, shift) when char in @upper_range, | |
| do: rem(char - @upper_start + shift, @letters_in_alphabet) + @upper_start | |
| defp do_rotate(char, shift) when char in @upper_range and shift >= 0, | |
| do: rem(char - @upper_start + shift, @letters_in_alphabet) + @upper_start | |
| defp do_rotate(char, shift) when char in @upper_range and shift < 0, | |
| do: rem(char - @upper_end + shift, @letters_in_alphabet) + @upper_end | |
| defp do_rotate(char, _), do: char | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment