2009-12-19 83 views
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」是否合理?

+1

爲了清晰起見,您可以添加函數的類型嗎? – 2009-12-19 13:52:18

回答

2

decyph key將解密後的文本作爲[Char]返回。隨着語法

n <- decyph k 
在列表理解

nChar類型和分配的解密文本的單個字符,但你想要的這裏是它被賦予的decyph全部結果,以便使它

let n = decyph k 

最後,檢查elem類型:

> :t elem 
elem :: (Eq a) => a -> [a] -> Bool 

與類型n[Char],第一個參數必須是Char,但是你有另一個字符串。如果你想與elems工作,你可以在口頭上分裂的破譯文字:

"the" `elem` words n 

這將編譯在這裏呢。

PS:假設 文本將包含字符串「the」是否合理?

這肯定是一個常見的英文單詞,但文字也可能會被全部大寫或the只可能在一個句子的開頭顯示爲The

相關問題