From 8d16541413cbc88856e5a5abb8a83f854b020731 Mon Sep 17 00:00:00 2001 From: Martin Potier Date: Thu, 10 Dec 2020 15:25:15 +0200 Subject: [PATCH] Day 9 - Part 2 Hope you have a fast machine. This is long to compute :) --- day9/main.hs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/day9/main.hs b/day9/main.hs index 1fa4e84..99bed8b 100755 --- a/day9/main.hs +++ b/day9/main.hs @@ -7,10 +7,13 @@ {-# OPTIONS_GHC -Wno-unused-top-binds -Wno-unused-imports #-} {-# LANGUAGE OverloadedStrings #-} +import Data.IntMap.Strict (IntMap) import Data.IntSet (IntSet) -import Data.List (tails) +import Data.List (inits, tails, sortOn) +import Data.Monoid import Debug.Trace (trace) import Text.Pretty.Simple +import qualified Data.IntMap.Strict as M import qualified Data.IntSet as S @@ -38,6 +41,23 @@ solvePart1 size message = where go xs = (head $ drop size xs,isSumOfPreamble size xs) + +-------------------------------------------------------------------------------- + +sortedContiguousSubLists :: [Int] -> [[Int]] +sortedContiguousSubLists = + dropWhile (== []) . sortOn length . concat . fmap inits . tails + +listSums :: [[Int]] -> IntMap [Int] +listSums xss = M.fromList $ do + xs <- xss + pure $ (getSum $ foldMap Sum xs, xs) + +solvePart2 :: Int -> [Int] -> Int +solvePart2 target message = (\x -> minimum x + maximum x) $ bigMap M.! target + where + bigMap = listSums $ sortedContiguousSubLists message + main :: IO () main = do putStrLn "Test" @@ -48,3 +68,8 @@ main = do print $ solvePart1 5 exampleData input <- lines <$> readFile "day9/input" print $ solvePart1 25 $ map read input + putStrLn "Test" + print $ take 10 $ drop 20 $ sortedContiguousSubLists exampleData + putStrLn "Day 9 - Part 2" + print $ solvePart2 127 exampleData + print $ solvePart2 3199139634 $ map read input