X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=advent05.hs;fp=advent05.hs;h=d86bd5aee32ee5301f82a3dc099b2e4eafcc604d;hb=fef438e522205404e0e765414e412ccacc34bfaa;hp=0000000000000000000000000000000000000000;hpb=f7a6219e119fedd3abd3d6967f1c6d104b04d8e4;p=advent-of-code-16.git diff --git a/advent05.hs b/advent05.hs new file mode 100644 index 0000000..d86bd5a --- /dev/null +++ b/advent05.hs @@ -0,0 +1,44 @@ +module Main(main) where + +import Data.Hash.MD5 (md5s, Str(..)) +import Data.List (isPrefixOf) +import qualified Data.Map.Lazy as Map + +type Password = Map.Map Integer Char + +input = "cxdnnyjw" + +main :: IO () +main = do + part1 + part2 + + +part1 :: IO () +part1 = do + print $ take 8 [h!!5 | h <- filter (interesting) $ md5sequence input 0] + +part2 :: IO () +part2 = do + print $ Map.foldr (:) [] password + where interestingHashes = + [(read [h!!5], h!!6) | + h <- filter (interesting) (md5sequence input 0), + h!!5 `elem` "01234567"] + password = findPassword Map.empty interestingHashes + + +md5sequence :: String -> Integer -> [String] +md5sequence key i = (md5s (Str (key ++ show i))) : (md5sequence key (i+1)) + +interesting :: String -> Bool +interesting hash = "00000" `isPrefixOf` hash + +dontReplace :: (Integer, Char) -> Password -> Password +dontReplace (k, v) = Map.insertWith (\_ v -> v) k v + +findPassword :: Password -> [(Integer, Char)] -> Password +findPassword p (candidate:candidates) + | Map.size p == 8 = p + | otherwise = findPassword p' candidates + where p' = dontReplace candidate p