From ba9b283d119df7930443394b073f4babd6e65b9d Mon Sep 17 00:00:00 2001 From: sgoudham Date: Sun, 4 Dec 2022 01:38:14 +0000 Subject: [PATCH] feat: complete day 3 --- advent-of-haskell.cabal | 2 +- solutions/Days/Day03.hs | 37 ++++++++++++++++++++++++++++++------- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/advent-of-haskell.cabal b/advent-of-haskell.cabal index 79c63c4..029f68d 100644 --- a/advent-of-haskell.cabal +++ b/advent-of-haskell.cabal @@ -11,7 +11,7 @@ build-type: Simple common common default-language: GHC2021 ghc-options: -Wall - default-extensions: RecordWildCards + default-extensions: RecordWildCards, OverloadedStrings executable runner import: common diff --git a/solutions/Days/Day03.hs b/solutions/Days/Day03.hs index 1447cc5..2ae166f 100644 --- a/solutions/Days/Day03.hs +++ b/solutions/Days/Day03.hs @@ -1,16 +1,39 @@ -module Days.Day03 (day03) where +module Days.Day03 (day03, splitInto, commonItem) where import AOC (Solution (..)) import qualified Data.Text as T +import Data.List +import Data.Maybe +import Debug.Trace day03 :: Solution day03 = Solution parseInput part1 part2 -parseInput :: T.Text -> a -parseInput = error "parseInput not defined for day 03" +parseInput :: T.Text -> [[String]] +parseInput input = go [] allLines + where + go acc [] = reverse acc + go acc xs = go (take 3 xs : acc) (drop 3 xs) + allLines = map T.unpack $ T.lines input -part1 :: a -> Int -part1 = error "part1 not defined for day 03" +priority :: Char -> Int +priority = (+1) . fromJust . flip elemIndex (['a'..'z'] ++ ['A'..'Z']) -part2 :: a -> Int -part2 = error "part2 not defined for day 03" +splitInto :: Int -> [a] -> [[a]] +splitInto s xs = go [] xs + where + go acc [] = reverse acc + go acc xs' = go (take takeInt xs' : acc) (drop takeInt xs') + takeInt = round $ (fromIntegral $ length xs) / (fromIntegral s) + +commonItem :: Eq a => [[a]] -> [a] +commonItem [] = [] +commonItem xs = foldl1' intersect xs + +part1 :: [[String]] -> Int +part1 input = sum $ map (priority . head . commonItem . splitInto 2) (concat input) + +part2 :: [[String]] -> Int +part2 input = sum $ map (priority . head . commonItem) input +-- part2 input = sum $ map (sum . map (priority . head . commonItem . splitInto 2)) (traceShowId input) +-- part2 input = traceShowId input