public
Created

Simple and probably slow caesar cipher in Haskell

  • Download Gist
Ashleigh cipher
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
-- If you want to use it type something like:
-- let tmp = encode 3 "Zombies ate my brains"
-- crack tmp
 
helper = zip ['a'..'z'] [0..25]
 
let2num::Char -> Int
let2num c = head [ b | (a,b) <- helper, a==c]
num2let d = head [ a | (a,b) <- helper, b==(d `mod` length helper)]
 
shift num c = if isLower c == False
then c
else num2let( (let2num c) + num )
 
encode::Int->String->String
encode num s = map (shift num) s
decode num s = map (shift ((length helper) - num)) s
 
lowers s = fromIntegral (length (filter isLower s ) )
count c s = fromIntegral (length (filter(==c) s) )
percent a b = (a/b)*100
freq::String->[Float]
freq s = [percent (count a s) (lowers s) | a<-['a'..'z']]
 
rotate::Int->String->String
rotate d s = (drop d s) ++ (take d s)
 
chisqr::[Float]->[Float]->Float
chisqr os es = sum [(a-b)^2/b | (a,b) <- zip os es]
 
position x xs = head [ b | (a,b) <- zip xs [0..(length xs -1)], a==x ]
 
freqArray s = [chisqr (freq (decode a s)) table | a <- [0..25]]
 
crack s = decode (position (minimum (freqArray s)) (freqArray s)) s
 
table::[Float]
table = [8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0,
0.2, 0.8, 4.0, 2.4, 6.7, 7.5, 1.9, 0.1, 6.0,
6.3, 9.1, 2.8, 1.0, 2.4, 0.2, 2.0, 0.1]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.