Last active
August 29, 2015 14:08
-
-
Save BennyHallett/72cb72c4a4f8274e2469 to your computer and use it in GitHub Desktop.
Caesar Cipher in Elixir
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 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