-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathedinburgh2.hs
More file actions
79 lines (63 loc) · 2.4 KB
/
Copy pathedinburgh2.hs
File metadata and controls
79 lines (63 loc) · 2.4 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
--- 1
rotate :: Int -> [Char] -> [Char]
rotate k list | k < 0 = error "Negative numbers not allowed."
| k > length list = error "Length too large."
| otherwise = take (length list) (drop k (cycle list))
--- 2
makeKey :: Int -> [(Char,Char)]
makeKey n = zip ['A'..'Z'] (rotate n ['A'..'Z'])
--- 3
lookUpRec :: Char -> [(Char, Char)] -> Char
lookUpRec c [] = c
lookUpRec c (t:tuples) | c == fst t = snd t
| otherwise = lookUpRec c tuples
--- 4
lookUp :: Char -> [(Char, Char)] -> Char
lookUp c tuples | null matches = c
| otherwise = head matches
where
matches = [snd t | t <- tuples, fst t == c]
--- 5
encipher :: Int -> Char -> Char
encipher k c = lookUp c (makeKey k)
--- 6
normalize :: String -> String
normalize s = [ toUpper c | c <- s, isAlphaNum c ]
--- 7
encipherStr :: Int -> String -> String
encipherStr k str = [ encipher k c | c <- normalize str ]
--- 8
reverseKey :: [(Char, Char)] -> [(Char, Char)]
reverseKey [] = []
reverseKey tuples = [ (snd t,fst t) | t <- tuples ]
--- 9
reverseKeyRec :: [(Char, Char)] -> [(Char, Char)]
reverseKeyRec []= []
reverseKeyRec (t:tuples) = [(snd t,fst t)] ++ reverseKeyRec tuples
--- 10
rotate :: Int -> [Char] -> [Char]
rotate k list | k < 0 = error "Negative numbers not allowed."
| k > length list = error "Length too large."
| otherwise = take (length list) (drop (26-k) (cycle list))
makeKey :: Int -> [(Char,Char)]
makeKey n = zip ['A'..'Z'] (rotate n ['A'..'Z'])
lookUp :: Char -> [(Char, Char)] -> Char
lookUp c tuples | null matches = c
| otherwise = head matches
where
matches = [snd t | t <- tuples, fst t == c]
decipher :: Int -> Char -> Char
decipher k c = lookUp c (makeKey k)
normalize :: String -> String
normalize s = [ toUpper c | c <- s, isAlphaNum c ]
decipherStr :: Int -> String -> String
decipherStr k str = [ decipher k c | c <- normalize str ]
--- 11
contains :: String -> String -> Bool
contains str s = if isInfixOf s str
then True
else False
--- 12
candidates :: String -> [(Int, String)]
candidates txt = [ (k,str) | (k,str) <- pairs, contains str "AND" || contains str "THE"]
where pairs = [(k,decipherStr k txt) | k <- [0..25]]