Skip to content

Instantly share code, notes, and snippets.

@BennyHallett BennyHallett/caesar.ex
Last active Aug 29, 2015

Embed
What would you like to do?
Caesar Cipher in Elixir
defmodule Caesar do
@doc """
Encode a file with a Caesar Cipher.
Shift value must be between 0 and 25. Works best with only aplha characters. Spaces will be left as spaces.
Usage:
$ iex caesar.ex
iex> Caesar.encode_file("/path/to/file", 13)
"""
def encode_file(file, value) do
file
|> File.read!
|> encode(value)
end
@doc """
Encode a string with a Caesar Cipher
Shift value must be between 0 and 25. Works best with only aplha characters. Spaces will be left as spaces.
Usage:
$ iex caesar.ex
iex> Caesar.encode("abc", 1)
"BCD"
"""
def encode(_, value) when value < 0, do: IO.puts "Value must be positive"
def encode(_, value) when value >= 26, do: IO.puts "Value must be less than 26"
def encode(text, value) do
text
|> String.upcase
|> String.codepoints
|> _encode(value)
|> Enum.join
end
defp _encode(codepoints, value), do: pmap(codepoints, &(encode_point(&1, value)))
defp encode_point(" ", _), do: " "
defp encode_point("\n", _), do: " "
defp encode_point(codepoint, value) do
<< p >> = codepoint
<< _encode_point(p + value) >>
end
defp _encode_point(p) when p > 90, do: p - 26
defp _encode_point(p), do: p
@doc """
PragDave's Parallel Map funcion
"""
defp pmap(list, f) do
me = self
list
|> Enum.map(fn(i) ->
spawn_link fn -> (send me, { self, f.(i) }) end
end)
|> Enum.map(fn (pid) ->
receive do { ^pid, result } -> result end
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.