Skip to content

Commit 7b0f421

Browse files
author
Bernard Pietraga
committed
Add exercise 2 from chapter 22
1 parent cafc64b commit 7b0f421

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

chapter_22/protocols_2.exs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
defprotocol CaesarSalad do
2+
def encrypt(string, shift)
3+
def rot13(string)
4+
end
5+
6+
defimpl CaesarSalad, for: List do
7+
def encrypt(list, shift), do:
8+
list |> Enum.map(&encrypt_char(&1, shift))
9+
10+
def rot13(list), do:
11+
encrypt(list, 13)
12+
13+
def encrypt_char(char, shift) when char in 97..122, do:
14+
97 + rem(char + shift - 97, 26)
15+
def encrypt_char(char, shift) when char in 65..90, do:
16+
65 + rem(char + shift - 65, 26)
17+
def encrypt_char(32, _shift), do:
18+
32
19+
# Question mark for not matched char
20+
def encrypt_char(_, _shift) do
21+
63
22+
end
23+
end
24+
25+
defimpl CaesarSalad, for: BitString do
26+
def encrypt(string, shift) do
27+
String.to_char_list(string)
28+
|> CaesarSalad.List.encrypt(shift)
29+
|> List.to_string
30+
end
31+
32+
def rot13(string), do:
33+
encrypt(string, 13)
34+
end
35+
36+
defmodule CaesarMacChecker do
37+
def run do
38+
mac_words = macintosh_dictionary()
39+
inspect_words(mac_words, sorted_words(mac_words))
40+
end
41+
42+
def inspect_words(mac_words, words_by_size) do
43+
Enum.each(mac_words, &match_word(&1, words_by_size))
44+
end
45+
46+
def match_word(word, words_by_size) do
47+
encrypted = CaesarSalad.rot13(word)
48+
case MapSet.member?(words_by_size[byte_size(word)], encrypted) do
49+
true ->
50+
IO.puts "#{word} is equal #{encrypted}"
51+
_ ->
52+
nil
53+
end
54+
end
55+
56+
def macintosh_dictionary do
57+
File.stream!("/usr/share/dict/words", [:read, :utf8], :line)
58+
|> Enum.map(&String.rstrip(&1) |> String.downcase)
59+
end
60+
61+
def sorted_words(words) do
62+
for {length, word_group} <- Enum.group_by(words, &byte_size/1), into: Map.new do
63+
{length, Enum.into(word_group, MapSet.new)}
64+
end
65+
end
66+
end
67+
68+
CaesarMacChecker.run

0 commit comments

Comments
 (0)