Created
January 26, 2011 08:41
-
-
Save lashleigh/796430 to your computer and use it in GitHub Desktop.
Simple and probably slow caesar cipher in Haskell
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
-- 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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment