Day 2 Part 2

This commit is contained in:
Nathan McCarty 2022-12-02 21:56:24 -05:00
parent ce30fd06f4
commit d64c5a83d3
Signed by: thatonelutenist
GPG Key ID: D70DA3DD4D1E9F96
1 changed files with 39 additions and 0 deletions

View File

@ -9,6 +9,13 @@ scoreResult Win = 6
scoreResult Loss = 0
scoreResult Draw = 3
-- Parse a result from a string
parseResult : String -> Maybe Result
parseResult "X" = Just Loss
parseResult "Y" = Just Draw
parseResult "Z" = Just Win
parseResult x = Nothing
data Move = Rock | Paper | Scissors
-- Determine the Result for a pair of moves
@ -40,6 +47,18 @@ parseMove "Y" = Just Paper
parseMove "Z" = Just Scissors
parseMove x = Nothing
-- Get the move that gives the desired result
getResult : Move -> Result -> Move
getResult Rock Win = Paper
getResult Rock Loss = Scissors
getResult Rock Draw = Rock
getResult Paper Win = Scissors
getResult Paper Loss = Rock
getResult Paper Draw = Paper
getResult Scissors Win = Rock
getResult Scissors Loss = Paper
getResult Scissors Draw = Scissors
data Round = R Move Move
-- Score a round
@ -57,12 +76,32 @@ parseRound input =
Just (R theirs ours)
x => Nothing
data Strategy = S Move Result
-- Create the round that results from this strategy
getRound : Strategy -> Round
getRound (S a b) = R a (getResult a b)
-- Parse a strategy from a string
parseStrategy : String -> Maybe Strategy
parseStrategy input =
let inputWords = words input
in case inputWords of
[a, b] =>
do theirs <- parseMove a
ours <- parseResult b
Just (S theirs ours)
x => Nothing
main: IO ()
main =
do file <- readFile "input"
case file of
Right content =>
let rounds = catMaybes . map parseRound . lines $ content
strats = catMaybes . map parseStrategy . lines $ content
in do putStr "Part 1: "
printLn $ foldl (+) 0 (map scoreRound rounds)
putStr "Part 2: "
printLn $ foldl (+) 0 (map scoreRound . map getRound $ strats)
Left err => printLn err