aoc23/day02b/src/Main.hs

35 lines
1.2 KiB
Haskell

{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
module Main (main) where
import Data.Text qualified as T
import Data.Text.Read (decimal)
parseVal :: [T.Text] -> (Integer, String)
parseVal [decimal @Integer -> Right cnt, name] = (fst cnt, T.unpack name)
parseVal _ = error "parseVal error"
parseVals :: T.Text -> [(Integer, String)]
parseVals vals = parseVal . T.split (== ' ') <$> T.splitOn (T.pack ", ") vals
parseParts :: [T.Text] -> (Integer, [[(Integer, String)]])
parseParts [T.words -> [T.unpack -> "Game", decimal @Integer -> Right d], values] = (fst d, parseVals <$> T.splitOn (T.pack "; ") values)
parseParts _ = error "parseParts error"
mapCubes :: T.Text -> (Integer, [[(Integer, String)]])
mapCubes line = parseParts $ T.splitOn (T.pack ": ") line
mergeMaxCube :: [(Integer, String)] -> (Integer, String) -> [(Integer, String)]
mergeMaxCube (h@(ax, colx) : xs) b@(ab, col)
| colx == col = (max ax ab, colx) : xs
| otherwise = h : mergeMaxCube xs b
mergeMaxCube [] v = [v]
main :: IO ()
main = do
lns <- lines <$> getContents
let values = mapCubes . T.pack <$> lns
print $ sum $ product . (fst <$>) . foldl mergeMaxCube [] . concat . snd <$> values