Parallel version, but consumes vast amounts of resources
[advent-of-code-16.git] / advent14parallel.hs
1 import Data.List (nub, tails)
2 import Data.ByteString.Char8 (pack)
3 import Crypto.Hash (hash, Digest, MD5)
4 import Control.Parallel.Strategies (parMap, rdeepseq)
5
6 salt = "yjdafjpo"
7 -- salt = "abc"
8
9 main :: IO ()
10 main = do
11 part1
12 part2
13
14 part1 :: IO ()
15 part1 = print $ head $ drop 63 $ filter (\i -> possibleKey sq i && confirmKey sq i) [0..]
16 where sq = md5sequence
17
18 part2 :: IO ()
19 part2 = print $ head $ drop 63 $ filter (\i -> possibleKey sq i && confirmKey sq i) [0..]
20 where sq = md5sequenceS
21
22 getHash :: String -> String
23 getHash bs = show (hash $ pack bs :: Digest MD5)
24
25 md5sequence :: [String]
26 -- md5sequence = [makeMd5 i | i <- [0..]]
27 md5sequence = parMap rdeepseq (makeMd5) [0..]
28 where makeMd5 i = getHash (salt ++ show i)
29
30 md5sequenceS :: [String]
31 -- md5sequenceS = [makeMd5 i | i <- [0..]]
32 md5sequenceS = parMap rdeepseq (makeMd5) [0..]
33 where makeMd5 i = stretch $ getHash (salt ++ show i)
34 stretch h0 = foldr (\_ h -> getHash h) h0 [1..2016]
35
36 possibleKey :: [String] -> Int-> Bool
37 possibleKey s = not . null . repeats 3 . ((!!) s)
38
39 confirmKey :: [String] -> Int -> Bool
40 confirmKey s i = any (confirmation) $ take 1000 $ drop (i+1) s
41 where c = head $ repeats 3 $ s!!i
42 confirmation m = c `elem` (repeats 5 m)
43
44 repeats :: Int -> String -> [String]
45 repeats n = filter (null . tail) . map (nub) . substrings n
46
47 substrings :: Int -> [a] -> [[a]]
48 substrings l = filter (\s -> (length s) == l) . map (take l) . tails