diff --git a/059-bis.c b/059-bis.c index 0ac7a8d..9d726e6 100644 --- a/059-bis.c +++ b/059-bis.c @@ -81,10 +81,16 @@ void fill_content(char *filename, Array content) { int rec_crack(Array content, Array code, Array decoded, char *buffer) { int i; char tmp[4]; + int sum=0; + char *str; if (code->length == code->max_length) { decode(content,code,decoded); if (potential_good_str(str_Array(decoded,buffer))) { fprintf(stderr,"Code: %s\nResult: %s\n",str_Array(code,tmp),buffer); + for (str=buffer; *str; str++) { + sum += *str; + } + fprintf(stderr, "Somme: %d\n",sum); } } else { if (code->length == 1) { @@ -102,8 +108,9 @@ int rec_crack(Array content, Array code, Array decoded, char *buffer) { int crack(Array content) { Array decoded=new_Array(content->max_length); Array code=new_Array(3); - char tmp[4]; char *buffer=(char *)malloc(2000); + /* + char tmp[4]; char *str; int sum; @@ -118,6 +125,7 @@ int crack(Array content) { } fprintf(stderr, "Somme: %d\n",sum); // --- + */ rec_crack(content,code,decoded,buffer); } diff --git a/059.hs b/059.hs index 19c5e18..155ca21 100644 --- a/059.hs +++ b/059.hs @@ -1,5 +1,20 @@ -import System +-- Source forum project haskell +import Data.Bits +import Data.Char +import Data.List + +keys = [ [a,b,c] | a <- [97..122], b <- [97..122], c <- [97..122] ] +allAlpha a = all (\k -> let a = ord k in ( a >= 32 && a <= 122)) a +howManySpaces x = length (elemIndices ' ' x) +compareBy f x y = compare (f x) (f y) main = do - [filename] <- readArgs - f <- open( + s <- readFile "cipher1.txt" + let + cipher = (read ("[" ++ s ++ "]") :: [Int]) + decrypts = [ (map chr (zipWith xor (cycle key) cipher), map chr key) | key <- keys ] + alphaDecrypts = filter (\(x,y) -> allAlpha x) decrypts + message = maximumBy (\(x,y) (x',y') -> compareBy howManySpaces x x') alphaDecrypts + asciisum = sum (map ord (fst message)) + putStrLn ("The message " ++ (fst message) ++ " was encoded with key " ++ (snd message)) + putStrLn (show asciisum) diff --git a/059.pl b/059.pl new file mode 100755 index 0000000..ad10d0a --- /dev/null +++ b/059.pl @@ -0,0 +1,19 @@ +#!/usr/bin/perl +# Source projecteuler.net forum +use List::Util qw/ sum /; +open(FILE,"cipher1.txt") or die ("Unable to open file"); +$cypher = join '', map { chr($_) } split /,/,; +$l = length $cypher; + +for my $key ('aaa' .. 'zzz') { + $text = $cypher ^ ( $key x int ($l/3) + . substr($key,0,$l%3) + ); + if ( $text =~ / and /i or $text =~ / the /i ) { + print "$key: $text$/"; + last; + } +} + +print "Ascii total: ", sum map { ord($_) } split //, $text; +print "\n";