2023 day 7: add Haskell solution

This commit is contained in:
eriedaberrie 2023-12-07 19:10:06 -08:00
parent 16e6d52927
commit 985b91b61c
2 changed files with 30 additions and 2 deletions

4
.gitignore vendored
View file

@ -2,8 +2,8 @@
*.o
*.hi
*data*.txt
main
main-[0-9]
[Mm]ain
[Mm]ain-[0-9]
# Nix stuff
result*

28
2023/7/Main.hs Normal file
View file

@ -0,0 +1,28 @@
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"