day2: update - use implement ordering like normal people

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2022-12-05 19:38:51 +05:30
parent 4c74b44b0d
commit 664cc4f6f8
2 changed files with 31 additions and 53 deletions

62
day2.hs
View File

@@ -2,54 +2,32 @@
main :: IO ()
main = do
input <- readFile "day2.in"
choices <- parse <$> readFile "day2.in"
putStr "Q1: "
print $ q1 input
print $ q1 choices
putStr "Q2: "
print $ q2 input
print $ q2 choices
data Choice = Rock | Paper | Scissors deriving (Enum, Eq)
q1 :: String -> Int
q1 =
sum
. map
( \[x, _, y] ->
let i = val x 'A'
j = val y 'X'
in fromEnum j + 1 + case () of
_
| i == j -> 3
| winCond i == j -> 6
| otherwise -> 0
)
. lines
instance Ord Choice where
compare x y | x == y = EQ
compare Rock Paper = LT
compare Paper Scissors = LT
compare Scissors Rock = LT
compare _ _ = GT
q2 :: String -> Int
q2 =
sum
. map
( \[x, _, y] ->
let i = val x 'A'
j = val y 'X'
in 1 + case fromEnum j of
0 -> 0 + fromEnum (loseCond i)
1 -> 3 + fromEnum i
2 -> 6 + fromEnum (winCond i)
)
. lines
parse :: String -> [(Choice, Choice)]
parse = map (\[x, _, y] -> (val x 'A', val y 'X')) . lines
score :: (Choice, Choice) -> Int
score (i, j) = 1 + fromEnum j + 3 * fromEnum (compare j i)
q1 :: [(Choice, Choice)] -> Int
q1 = sum . map score
q2 :: [(Choice, Choice)] -> Int
q2 = sum . map (score . \(i, j) -> (i, toEnum $ mod (fromEnum i + fromEnum j + 2) 3))
val :: Char -> Char -> Choice
val a b = toEnum (fromEnum a - fromEnum b) :: Choice
winCond :: Choice -> Choice
winCond c = case c of
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
loseCond :: Choice -> Choice
loseCond c = case c of
Paper -> Rock
Scissors -> Paper
Rock -> Scissors