Created
May 26, 2012 15:46
-
-
Save svdberg/2794373 to your computer and use it in GitHub Desktop.
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
import Data.List | |
import Data.List.Split | |
import Data.Char | |
import qualified Data.Map as Map | |
import Data.List.HT | |
type Password = String | |
type Direction = Int | |
--new implementation: change Cipher to Map | |
--newchipher is a map from a place in the cipher matrix to a character | |
type NewCipher = Map.Map (Int,Int) Char | |
buildCipher :: Password -> NewCipher | |
buildCipher pw = Map.fromList $ zip chessBoard (concat $ build pw) | |
where | |
chessBoard = [ (x,y) | x <- [0..4], y <- [0..4] ] | |
build = chunk 5 . (`union` delete 'J' ['A'..'Z']) . nub . process --calculate the list of characters in the right order | |
process :: String -> String | |
process = replace "J" "I" . map toUpper . filter isLetter | |
--safely get a Char from the Map | |
get :: NewCipher -> (Int,Int) -> Char | |
get m (x,y) = m Map.! (mod x 5, mod y 5) | |
newEncode :: NewCipher -> String -> String | |
newEncode _ [] = [] | |
newEncode c [x] = newEncode c (x : "X") --always at the end of the message | |
newEncode c (x:y:xs) | (x==y) = newEncode c [x] ++ newEncode c (y:xs) | |
| otherwise = code c 1 x y ++ newEncode c xs | |
findCharInCipher :: NewCipher -> Char -> (Int,Int) | |
findCharInCipher k c = head . Map.keys $ Map.filter (==c) k | |
code :: NewCipher -> Direction -> Char -> Char -> String | |
code c dir a b | |
| y1 == y2 = get c (x1 + dir, y1) : [get c (x2 + dir, y2)] --same col | |
| x1 == x2 = get c (x1, y1 + dir) : [get c (x2, y2 + dir)] --same row | |
| otherwise = get c (x1, y2) : [get c (x2, y1)] | |
where | |
(x1, y1) = findCharInCipher c a | |
(x2, y2) = findCharInCipher c b | |
newDecode :: NewCipher -> String -> String | |
newDecode k = concatMap (\[x,y] -> code k (-1) x y) . chunk 2 | |
encode :: String -> Password -> String | |
encode m k = (newEncode (buildCipher k) . process) m | |
decode :: String -> Password -> String | |
decode m k = (newDecode (buildCipher k) . process) m | |
main :: IO () | |
main = do print $ encode "PROGRAMMING PRAXIS" "PLAYFAIR" | |
print $ decode "LIVOBLKZEDOELIYWCN" "PLAYFAIR" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks nice, I'll try a scala version ;)