Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Last active June 6, 2017 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rstacruz/220b192e370811ef05a96f6f3a18ee81 to your computer and use it in GitHub Desktop.
Save rstacruz/220b192e370811ef05a96f6f3a18ee81 to your computer and use it in GitHub Desktop.
Rot13 in Elixir
defmodule Rotator do
def encode(string, shift \\ 13)
def encode(<<char>> <> tail, shift) do
<<rotate(char, shift)>> <> encode(tail, shift)
end
def encode(_, _), do: ""
def rotate(char, shift) when ((char >= ?a) and (char <= ?z)) do
?a + rem(char - ?a + shift, 26)
end
def rotate(char, shift) when ((char >= ?A) and (char <= ?Z)) do
?A + rem(char - ?A + shift, 26)
end
def rotate(char, _), do: char
end
IO.puts Rotator.encode("Attack at dawn!") #=> "Nggnpx ng qnja!"
IO.puts Rotator.encode("Attack at dawn!", 1) #=> "Buubdl bu ebxo!"
IO.puts Rotator.encode("Attack at dawn!", 0) #=> "Attack at dawn!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment