From 4ec9d323c2a49d9d9f39e143c37607a3ca17356b Mon Sep 17 00:00:00 2001 From: Stefan Dresselhaus Date: Mon, 5 Dec 2022 00:30:20 +0100 Subject: [PATCH] day3 done --- AoC2022.cabal | 14 ++++++++++++++ day2/Main.hs | 10 ---------- day3/Main.hs | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 10 deletions(-) create mode 100644 day3/Main.hs diff --git a/AoC2022.cabal b/AoC2022.cabal index 0131627..0e967cb 100644 --- a/AoC2022.cabal +++ b/AoC2022.cabal @@ -48,3 +48,17 @@ executable Day2 , safe hs-source-dirs: day2 default-language: Haskell2010 + +executable Day3 + main-is: Main.hs + + -- Modules included in this executable, other than Main. + -- other-modules: + + -- LANGUAGE extensions used by modules in this package. + -- other-extensions: + build-depends: base ^>=4.14.3.0 + , safe + , extra + hs-source-dirs: day3 + default-language: Haskell2010 diff --git a/day2/Main.hs b/day2/Main.hs index b858978..b453a71 100644 --- a/day2/Main.hs +++ b/day2/Main.hs @@ -92,13 +92,3 @@ result 'X' = Loss result 'Y' = Draw result 'Z' = Win result c = error $ "malformed Input: "<> show c - --- | Split a list into sublists delimited by the given element. --- --- From: https://hackage.haskell.org/package/haskell-gi-0.26.2/docs/src/Data.GI.CodeGen.Util.html#splitOn -splitOn :: Eq a => a -> [a] -> [[a]] -splitOn x xs = go xs [] - where go [] acc = [reverse acc] - go (y : ys) acc = if x == y - then reverse acc : go ys [] - else go ys (y : acc) diff --git a/day3/Main.hs b/day3/Main.hs new file mode 100644 index 0000000..2e5e16c --- /dev/null +++ b/day3/Main.hs @@ -0,0 +1,52 @@ +{-# LANGUAGE LambdaCase #-} +module Main where + +import Data.List as L +import Data.Bifunctor +import Data.Char +import Data.Maybe +import Data.List.Extra +import Safe + +data InputOptions = SumPrios + | SumGroups + | Quit + + +getInput :: IO InputOptions +getInput = do + putStrLn "Sum Prios or Quit? (s/g/q)" + getLine >>= \case + "s" -> return SumPrios + "g" -> return SumGroups + "q" -> return Quit + _ -> putStrLn "not understood" >> getInput + +main :: IO () +main = getInput >>= \case + Quit -> putStrLn "bye!" + SumPrios -> interact $ + (<>"\n") + . show + . sum + . fmap turnIntoPrios + . lines + SumGroups -> interact $ + (<>"\n") + . show + . sum + . fmap turnIntoGroup + . chunksOf 3 + . lines + +turnIntoPrios :: String -> Integer +turnIntoPrios l = maximum . fmap toPrio . uncurry intersect . bimap sort sort . splitAt (length l `div` 2) $ l + +turnIntoGroup :: [String] -> Integer +turnIntoGroup [a,b,c] = maximum . fmap toPrio $ intersect a (b `intersect` c) + +toPrio :: Char -> Integer +toPrio x + | isAsciiLower x = toInteger $ ord x - ord 'a' + 1 + | isAsciiUpper x = toInteger $ ord x - ord 'A' + 27 + | otherwise = error "malformed input"