Broke days into individual pacakges
[advent-of-code-16.git] / adventofcode1614 / app / advent14.hs
1 module Main(main) where
2
3 import Data.List (nub, tails, null)
4 import Data.Hash.MD5 (md5s, Str(..))
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 md5sequence :: [String]
23 md5sequence = [makeMd5 i | i <- [0..]]
24 where makeMd5 i = md5s (Str (salt ++ show i))
25
26 md5sequenceS :: [String]
27 md5sequenceS = [makeMd5 i | i <- [0..]]
28 where makeMd5 i = stretch $ md5s (Str (salt ++ show i))
29 stretch h0 = foldr (\_ h -> md5s (Str h)) h0 [1..2016]
30
31 possibleKey :: [String] -> Int-> Bool
32 possibleKey s = not . null . repeats 3 . ((!!) s)
33
34 confirmKey :: [String] -> Int -> Bool
35 confirmKey s i = any (confirmation) $ take 1000 $ drop (i+1) s
36 where c = head $ repeats 3 $ s!!i
37 confirmation m = c `elem` (repeats 5 m)
38
39 repeats :: Int -> String -> [String]
40 repeats n = filter (null . tail) . map (nub) . substrings n
41
42 substrings :: Int -> [a] -> [[a]]
43 substrings l = filter (\s -> (length s) == l) . map (take l) . tails