Created
September 9, 2024 06:57
-
-
Save themaxhero/fa299f99e318278a9a4c0e7e5416aa2a to your computer and use it in GitHub Desktop.
This file contains 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 CeasarCipher do | |
@lower Enum.to_list(?a..?z) | |
@upper Enum.to_list(?A..?Z) | |
defp map_within_range(c, range, shift) do | |
if c in range do | |
range | |
|> Stream.cycle() | |
|> Stream.drop(shift + (c - hd(range))) | |
|> Stream.take(1) | |
else | |
[c] | |
end | |
end | |
defp mapping(c, shift) when c in @lower, | |
do: map_within_range(c, @lower, shift) | |
defp mapping(c, shift) when c in @upper, | |
do: map_within_range(c, @upper, shift) | |
defp mapping(c, _shift), | |
do: [c] | |
def encode(string, shift) do | |
string | |
|> String.to_charlist() | |
|> Stream.flat_map(&mapping(&1, shift)) | |
|> Enum.to_list() | |
|> to_string() | |
end | |
def decode(string, shift) do | |
encode(string, length(@lower) - shift) | |
end | |
end | |
string = "Hello World" | |
target_shift = 10 | |
string | |
|> CeasarCipher.encode(target_shift) | |
|> IO.inspect() | |
|> CeasarCipher.decode(target_shift) | |
|> IO.inspect() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment