diff --git a/lib/ciphers/rot13.ex b/lib/ciphers/rot13.ex new file mode 100644 index 0000000..48fe1bd --- /dev/null +++ b/lib/ciphers/rot13.ex @@ -0,0 +1,36 @@ +defmodule Algorithms.Ciphers.Rot13 do + @moduledoc """ + subtition cipher for alphabets by rotating about the alphabet list 13 places (https://en.wikipedia.org/wiki/ROT13) + + ## Parameters + + - text: Input number to insert the a new bit. + + ## Examples + + iex> Rot13.encode("hello") + 14 + """ + + def encode(string) + + def encode(<> <> tail) do + <> <> encode(tail) + end + + def encode(_), do: "" + + def rotate(char) when char >= ?a and char <= ?z do + ?a + rem(char - ?a + 13, 26) + end + + def rotate(char) when char >= ?A and char <= ?Z do + ?A + rem(char - ?A + 13, 26) + end + + def rotate(char), do: char + + def decode(string) do + encode(string) + end +end diff --git a/test/ciphers/rot13.exs b/test/ciphers/rot13.exs new file mode 100644 index 0000000..f82f362 --- /dev/null +++ b/test/ciphers/rot13.exs @@ -0,0 +1,34 @@ +defmodule Algorithms.Ciphers.Rot13Test do + alias Algorithms.Ciphers.Rot13 + + use ExUnit.Case + + test "encode and decode" do + assert Rot13.encode("Hello, World!") == "Uryyb, Jbeyq!" + assert Rot13.decode("Uryyb, Jbeyq!") == "Hello, World!" + end + + test "encode and decode with uppercase letters" do + assert Rot13.encode("HELLO, WORLD!") == "URYYB, JBEYQ!" + assert Rot13.decode("URYYB, JBEYQ!") == "HELLO, WORLD!" + end + + test "encode and decode with special characters" do + assert Rot13.encode("Hello, World! @#$%^&*()") == "Uryyb, Jbeyq! @#$%^&*()" + assert Rot13.decode("Uryyb, Jbeyq! @#$%^&*()") == "Hello, World! @#$%^&*()" + end + + describe "Rot13.encode/1" do + test "encodes a string" do + assert Rot13.encode("Hello, World!") == "Uryyb, Jbeyq!" + end + + test "encodes a string with uppercase letters" do + assert Rot13.encode("HELLO, WORLD!") == "URYYB, JBEYQ!" + end + + test "encodes a string with special characters" do + assert Rot13.encode("Hello, World! @#$%^&*()") == "Uryyb, Jbeyq! @#$%^&*()" + end + end +end