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