From 985b91b61cbd882a334fab458919c5167d079c93 Mon Sep 17 00:00:00 2001 From: eriedaberrie Date: Thu, 7 Dec 2023 19:10:06 -0800 Subject: [PATCH] 2023 day 7: add Haskell solution --- .gitignore | 4 ++-- 2023/7/Main.hs | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 2023/7/Main.hs diff --git a/.gitignore b/.gitignore index e2c9fa5..592f45e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,8 @@ *.o *.hi *data*.txt -main -main-[0-9] +[Mm]ain +[Mm]ain-[0-9] # Nix stuff result* diff --git a/2023/7/Main.hs b/2023/7/Main.hs new file mode 100644 index 0000000..3a5746c --- /dev/null +++ b/2023/7/Main.hs @@ -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"