0
對於項目歐拉59,我想出了這個返回包含該decyphered字符串元組的列表,並使用的密鑰(是的,我知道Data.Bits
):返回一個decyphered字符串作爲元組的一部分,在Haskell
module XOR where
import Data.List
import Data.Char
decToBin :: Integer -> [Integer]
decToBin x = reverse $ decToBin' x
where
decToBin' 0 = []
decToBin' y = let (a,b) = quotRem y 2 in [b] ++ decToBin' a
binToDec :: [Integer] -> Integer
binToDec xs = foldl (+) 0 $ map (\(x,y) -> x*(2^y)) $reverse $ zip (reverse xs) [0..]
bitwise f x y = zipWith f x y
lenBin :: Integer -> Integer
lenBin x= length$ decToBin x
xor :: Integer -> Integer -> Bool
xor x y | x == y = 0
| x /= y = 1
| otherwise = error "Impossible"
bitwiseXOR :: Integer -> Integer -> Integer
bitwiseXOR a b | (lenBin a) > (lenBin b) = binToDec $ bitwise xor ((replicate ((lenBin a) - (lenBin b)) 0)++(decToBin b)) (decToBin a)
| (lenBin a) < (lenBin b) = binToDec $ bitwise xor ((replicate ((lenBin b) - (lenBin a)) 0)++(decToBin a)) (decToBin b)
| otherwise =binToDec $ bitwise xor (decToBin b) (decToBin a)
decyph :: [char] -> [char]
decyph key = map chr $ map (\(x,y)-> bitwiseXOR x (ord y)) $ zip numbers $ cycle key
brute :: [([Char],[Char])]
brute = [(n,k)|k<- (sequence $ replicate 3 ['a'..'z']) ,n <- decyph k, "the" `isInfixOf` n]
numbers :: [Integer]
numbers = [79,59,12,2,79,35,8...]
問題是,當我不能運行decyph
,因爲它生成的元組只包含第一部分中的一個字符和第二部分中的密鑰,而不是使用所用密鑰的整個解密文本。我怎樣才能解決這個問題?
PS:假設文本中包含字符串「the」是否合理?
爲了清晰起見,您可以添加函數的類型嗎? – 2009-12-19 13:52:18