Background
I am trying to do the typical Ceaser cypher exercise in Elixir. The description of the exercise is as follows:
Create an implementation of the rotational cipher, also sometimes called the Caesar cipher.
The Caesar cipher is a simple shift cipher that relies on transposing all the letters in the alphabet using an integer key between
0
and26
. Using a key of0
or26
will always yield the same output due to modular arithmetic. The letter is shifted for as many values as the value of the key.The general notation for rotational ciphers is
ROT + <key>
. The most commonly used rotational cipher isROT13
.
Code
To achieve this I made some research and came up with the following solution which doesn’t work:
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"
"""
@spec rotate(text :: String.t(), shift :: integer) :: String.t()
def rotate(text, shift) do
text
|> String.to_charlist()
|> Enum.map( fn char -> char < 97 || 97 + rem( char - 71 - shift, 26 ) end )
|> to_string()
end
end
For example, if I call RotationalCipher.rotate("a", 1)
instead of b
, I get z
.
Now since the objective here is to work with strings, I am fairly confident I am not converting the string correctly to it’s bitstring equivalent ( https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html ).
I have read the documentation and searched for several functions but I am clearly missing something.
Question
Which bitstring function should I be using ?