-
Notifications
You must be signed in to change notification settings - Fork 0
/
shift.ex
56 lines (45 loc) · 1.21 KB
/
shift.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
defmodule ShiftCipher do
def encrypt(value, key) when key > 0 do
shift(String.graphemes(value), :left, key)
end
def decrypt(value, key) when key > 0 do
to_string(shift(value, :right, key))
end
defp shift([], direction, _) do
cond do
direction == :right or direction == :left ->
[]
direction ->
{:error}
end
end
defp shift([a], direction, _) do
cond do
direction == :right or direction == :left ->
[a]
direction ->
{:error}
end
end
defp shift([head | tail], direction, 1) when is_atom(direction) and is_list([head | tail]) do
cond do
direction == :right ->
[List.last(tail) | [head | tail |> Enum.reverse() |> tl() |> Enum.reverse()]]
direction == :left ->
tail ++ [head]
direction ->
{:error}
end
end
defp shift([head | tail], direction, n)
when is_atom(direction) and is_list([head | tail]) and n > 0 do
cond do
direction == :right ->
shift(shift([head | tail], direction, 1), direction, n - 1)
direction == :left ->
shift(shift([head | tail], direction, 1), direction, n - 1)
direction ->
{:error}
end
end
end