advent-of-code/2023/7/Main.hs
2023-12-12 20:25:25 -08:00

40 lines
937 B
Haskell

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