1 -- Writeup at https://work.njae.me.uk/2022/12/02/advent-of-code-2022-day-2/
3 import System.Environment
5 import qualified Data.Text.IO as TIO
6 import Data.Attoparsec.Text hiding (Result)
7 import Control.Applicative
9 data Shape = Rock | Paper | Scissors deriving (Show, Eq, Ord, Enum)
10 data Result = Loss | Draw | Win deriving (Show, Eq, Ord, Enum)
11 data Round = Round Shape Shape deriving (Eq, Show)
12 data ShapeResult = ShapeResult Shape Result deriving (Eq, Show)
16 do dataFileName <- getDataFileName
17 text <- TIO.readFile dataFileName
18 let match1 = successfulParse1 text
20 let match2 = successfulParse2 text
23 getDataFileName :: IO String
26 progName <- getProgName
27 let baseDataName = if null args
30 let dataFileName = "data/" ++ baseDataName ++ ".txt"
33 part1 :: [Round] -> Int
34 part1 = sum . fmap scoreRound
36 part2 :: [ShapeResult] -> Int
37 part2 = sum . fmap (scoreRound . roundFromResult)
39 player2Result :: Round -> Result
40 player2Result (Round Rock Paper) = Win
41 player2Result (Round Paper Scissors) = Win
42 player2Result (Round Scissors Rock) = Win
43 player2Result (Round x y) | x == y = Draw
44 player2Result _ = Loss
46 scoreRound :: Round -> Int
47 scoreRound r@(Round _ y) = scoreShape y + scoreResult (player2Result r)
49 scoreShape :: Shape -> Int
50 scoreShape s = 1 + fromEnum s
52 scoreResult :: Result -> Int
53 scoreResult r = 3 * fromEnum r
55 roundFromResult :: ShapeResult -> Round
56 roundFromResult (ShapeResult shape result) = Round shape p2s
57 where p2s = head [ p2Shape
58 | p2Shape <- [Rock .. Scissors]
59 , player2Result (Round shape p2Shape) == result
62 -- Parse the input file
64 match1P = roundP `sepBy` endOfLine
65 roundP = Round <$> p1ShapeP <*> (" " *> p2ShapeP)
67 match2P = shapeResultP `sepBy` endOfLine
68 shapeResultP = ShapeResult <$> p1ShapeP <*> (" " *> resultP)
70 p1ShapeP = aP <|> bP <|> cP
75 p2ShapeP = xP <|> yP <|> zP
80 resultP = xrP <|> yrP <|> zrP
85 -- successfulParse :: Text -> (Integer, [Maybe Integer])
86 successfulParse1 input =
87 case parseOnly match1P input of
88 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
91 successfulParse2 input =
92 case parseOnly match2P input of
93 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err