Day 9 - Part 2

Hope you have a fast machine. This is long to compute :)
This commit is contained in:
Martin Potier 2020-12-10 15:25:15 +02:00
parent 0305b145a7
commit 8d16541413
No known key found for this signature in database
GPG Key ID: D4DD957DBA4AD89E
1 changed files with 26 additions and 1 deletions

View File

@ -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