Created
August 15, 2011 05:16
-
-
Save draftcode/1145746 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import Data.Char | |
| positions :: (Eq a) => a -> [a] -> [Int] | |
| positions t xs = [n | (x,n) <- zip xs [0..(length xs)-1], x == t] | |
| count :: Char -> String -> Int | |
| count c (x:xs) | c == x = 1 + count c xs | |
| | otherwise = count c xs | |
| count _ [] = 0 | |
| lowers :: String -> Int | |
| lowers xs = sum [1 | x <- xs, isLower x] | |
| let2int :: Char -> Int | |
| let2int c = ord c - ord 'a' | |
| int2let :: Int -> Char | |
| int2let n = chr (ord 'a' + n) | |
| shift :: Int -> Char -> Char | |
| shift n c | isLower c = int2let((let2int c + n) `mod` 26) | |
| | otherwise = c | |
| encode :: Int -> String -> String | |
| encode n xs = [shift n x | x <- xs] | |
| 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] | |
| percent :: Int -> Int -> Float | |
| percent n m = (fromIntegral n / fromIntegral m) * 100 | |
| freqs :: String -> [Float] | |
| freqs xs = [percent (count x xs) n | x <- ['a'..'z']] | |
| where n = lowers xs | |
| chisqr :: [Float] -> [Float] -> Float | |
| chisqr os es = sum [((o - e)^2) / e | (o,e) <- zip os es] | |
| rotate :: Int -> [a] -> [a] | |
| rotate n xs = drop n xs ++ take n xs | |
| crack :: String -> String | |
| crack xs = encode (-factor) xs | |
| where | |
| factor = head (positions (minimum chitab) chitab) | |
| chitab = [chisqr (rotate n table') table | n <- [0..25]] | |
| table' = freqs xs | |
| -- crack "kdvnhoo lv ixq" | |
md2perpe
commented
Aug 15, 2011
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment