X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=advent02%2FMain.hs;h=074157a0d9bdd8f6b50ed9695deed1875861f00a;hb=refs%2Fheads%2Fmain;hp=9cb89cc02be4dc4faa67d1ec62aedc12ede4ec05;hpb=c4a6729c94fcad21b4c3f26cec8ff2d4c15c1b6e;p=advent-of-code-22.git diff --git a/advent02/Main.hs b/advent02/Main.hs index 9cb89cc..074157a 100644 --- a/advent02/Main.hs +++ b/advent02/Main.hs @@ -1,12 +1,12 @@ -- Writeup at https://work.njae.me.uk/2022/12/02/advent-of-code-2022-day-2/ -import System.Environment -import Data.Text () +import AoC +import Data.Text (Text) import qualified Data.Text.IO as TIO import Data.Attoparsec.Text hiding (Result) import Control.Applicative -data Shape = Rock | Paper | Scissors deriving (Show, Eq, Ord, Enum) +data Shape = Rock | Paper | Scissors deriving (Show, Eq, Ord, Enum, Bounded) data Result = Loss | Draw | Win deriving (Show, Eq, Ord, Enum) data Round = Round Shape Shape deriving (Eq, Show) data ShapeResult = ShapeResult Shape Result deriving (Eq, Show) @@ -20,16 +20,6 @@ main = let match2 = successfulParse2 text print $ part2 match2 -getDataFileName :: IO String -getDataFileName = - do args <- getArgs - progName <- getProgName - let baseDataName = if null args - then progName - else head args - let dataFileName = "data/" ++ baseDataName ++ ".txt" - return dataFileName - part1 :: [Round] -> Int part1 = sum . fmap scoreRound @@ -55,12 +45,20 @@ scoreResult r = 3 * fromEnum r roundFromResult :: ShapeResult -> Round roundFromResult (ShapeResult shape result) = Round shape p2s where p2s = head [ p2Shape - | p2Shape <- [Rock .. Scissors] + -- | p2Shape <- [Rock .. Scissors] + | p2Shape <- [minBound .. maxBound] , player2Result (Round shape p2Shape) == result ] -- Parse the input file +match1P :: Parser [Round] +match2P :: Parser [ShapeResult] +roundP :: Parser Round +shapeResultP :: Parser ShapeResult +p1ShapeP, p2ShapeP, aP, bP, cP, xP, yP, zP :: Parser Shape +resultP, xrP, yrP, zrP :: Parser Result + match1P = roundP `sepBy` endOfLine roundP = Round <$> p1ShapeP <*> (" " *> p2ShapeP) @@ -82,13 +80,14 @@ xrP = Loss <$ "X" yrP = Draw <$ "Y" zrP = Win <$ "Z" --- successfulParse :: Text -> (Integer, [Maybe Integer]) +successfulParse1 :: Text -> [Round] successfulParse1 input = case parseOnly match1P input of Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err - Right match -> match + Right matches -> matches +successfulParse2 :: Text -> [ShapeResult] successfulParse2 input = case parseOnly match2P input of Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err - Right match -> match + Right matches -> matches