advent-of-code/2023/7/Main.hs

40 lines
937 B
Haskell
Raw Normal View History

2023-12-12 20:25:25 -08:00
import Data.Bifunctor (second)
import Data.List (group, sort, sortOn)
2023-12-07 19:10:06 -08:00
import qualified Data.HashMap.Strict as HMS
cardOrder :: HMS.HashMap Char Int
2023-12-12 20:25:25 -08:00
cardOrder = HMS.fromList . zip "AKQT98765432J" $ [0 ..]
2023-12-07 19:10:06 -08:00
getWorth :: String -> [Int]
2023-12-12 20:25:25 -08:00
getWorth cards = handType:map (cardOrder HMS.!) cards
2023-12-07 19:10:06 -08:00
where
noJs = filter (/= 'J') cards
2023-12-12 20:25:25 -08:00
2023-12-07 19:10:06 -08:00
jCount = 5 - length noJs
2023-12-12 20:25:25 -08:00
groupedCards = map length . group . sort $ noJs
2023-12-07 19:10:06 -08:00
handType = case length groupedCards of
0 -> 1
1 -> 1
2023-12-12 20:25:25 -08:00
2 -> if minimum groupedCards == 1
then 2
else 3
3 -> if maximum groupedCards + jCount == 3
then 4
else 5
2023-12-07 19:10:06 -08:00
4 -> 6
5 -> 7
solve :: [String] -> Int
2023-12-12 20:25:25 -08:00
solve = sum
. zipWith (*) [1 ..]
. map snd
. sortOn (map negate . getWorth . fst)
. map parseLine
2023-12-07 19:10:06 -08:00
where
parseLine = second read . splitAt 5
main :: IO ()
main = print . solve . lines =<< readFile "data.txt"