From d64c5a83d3f3d1be2d7ffa69e89118b5b91d274e Mon Sep 17 00:00:00 2001 From: Nathan McCarty Date: Fri, 2 Dec 2022 21:56:24 -0500 Subject: [PATCH] Day 2 Part 2 --- 02/Main.idr | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/02/Main.idr b/02/Main.idr index 733d0e9..1dcb13c 100644 --- a/02/Main.idr +++ b/02/Main.idr @@ -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