231531749fb68bb0ca9d11b7654e15eb3ae06c47
[advent-of-code-22.git] / advent02 / Main.hs
1 -- Writeup at https://work.njae.me.uk/2022/12/02/advent-of-code-2022-day-2/
2
3 import AoC
4 import Data.Text ()
5 import qualified Data.Text.IO as TIO
6 import Data.Attoparsec.Text hiding (Result)
7 import Control.Applicative
8
9 data Shape = Rock | Paper | Scissors deriving (Show, Eq, Ord, Enum, Bounded)
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)
13
14 main :: IO ()
15 main =
16 do dataFileName <- getDataFileName
17 text <- TIO.readFile dataFileName
18 let match1 = successfulParse1 text
19 print $ part1 match1
20 let match2 = successfulParse2 text
21 print $ part2 match2
22
23 part1 :: [Round] -> Int
24 part1 = sum . fmap scoreRound
25
26 part2 :: [ShapeResult] -> Int
27 part2 = sum . fmap (scoreRound . roundFromResult)
28
29 player2Result :: Round -> Result
30 player2Result (Round Rock Paper) = Win
31 player2Result (Round Paper Scissors) = Win
32 player2Result (Round Scissors Rock) = Win
33 player2Result (Round x y) | x == y = Draw
34 player2Result _ = Loss
35
36 scoreRound :: Round -> Int
37 scoreRound r@(Round _ y) = scoreShape y + scoreResult (player2Result r)
38
39 scoreShape :: Shape -> Int
40 scoreShape s = 1 + fromEnum s
41
42 scoreResult :: Result -> Int
43 scoreResult r = 3 * fromEnum r
44
45 roundFromResult :: ShapeResult -> Round
46 roundFromResult (ShapeResult shape result) = Round shape p2s
47 where p2s = head [ p2Shape
48 -- | p2Shape <- [Rock .. Scissors]
49 | p2Shape <- [minBound .. maxBound]
50 , player2Result (Round shape p2Shape) == result
51 ]
52
53 -- Parse the input file
54
55 match1P = roundP `sepBy` endOfLine
56 roundP = Round <$> p1ShapeP <*> (" " *> p2ShapeP)
57
58 match2P = shapeResultP `sepBy` endOfLine
59 shapeResultP = ShapeResult <$> p1ShapeP <*> (" " *> resultP)
60
61 p1ShapeP = aP <|> bP <|> cP
62 aP = Rock <$ "A"
63 bP = Paper <$ "B"
64 cP = Scissors <$ "C"
65
66 p2ShapeP = xP <|> yP <|> zP
67 xP = Rock <$ "X"
68 yP = Paper <$ "Y"
69 zP = Scissors <$ "Z"
70
71 resultP = xrP <|> yrP <|> zrP
72 xrP = Loss <$ "X"
73 yrP = Draw <$ "Y"
74 zrP = Win <$ "Z"
75
76 -- successfulParse :: Text -> (Integer, [Maybe Integer])
77 successfulParse1 input =
78 case parseOnly match1P input of
79 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
80 Right match -> match
81
82 successfulParse2 input =
83 case parseOnly match2P input of
84 Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err
85 Right match -> match