r/adventofcode • • Dec 02 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 2 Solutions -🎄-

NEW AND NOTEWORTHY


--- Day 2: Rock Paper Scissors ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:06:16, megathread unlocked!

103 Upvotes

1.5k comments sorted by

View all comments

1

u/NeilNjae Dec 02 '22

Haskell

This one ended up as an exercise in parsing and representation, rather than solving the challenges. Represent the game as a game, and all becomes easy.

Full writeup on my blog, and code on Gitlab.

data Shape = Rock | Paper | Scissors deriving (Show, Eq, Ord, Enum)
data Result = Loss | Draw | Win deriving (Show, Eq, Ord, Enum)
data Round = Round Shape Shape deriving (Eq, Show)
data ShapeResult = ShapeResult Shape Result deriving (Eq, Show)

match1P = roundP `sepBy` endOfLine
roundP = Round <$> p1ShapeP <*> (" " *> p2ShapeP)

match2P = shapeResultP `sepBy` endOfLine
shapeResultP = ShapeResult <$> p1ShapeP <*> (" " *> resultP)

p1ShapeP = aP <|> bP <|> cP
aP = Rock <$ "A"
bP = Paper <$ "B"
cP = Scissors <$ "C"

p2ShapeP = xP <|> yP <|> zP
xP = Rock <$ "X"
yP = Paper <$ "Y"
zP = Scissors <$ "Z"

resultP = xrP <|> yrP <|> zrP
xrP = Loss <$ "X"
yrP = Draw <$ "Y"
zrP = Win <$ "Z"

1

u/daggerdragon Dec 05 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.

1

u/levital Dec 02 '22

I like the way to compute the second shape in part 2. I briefly looked at automated function inversion, but quickly decided that just enumerating it manually would be much easier. Just trying all possibilities automatically is something I really could've thought of. :D

1

u/NeilNjae Dec 03 '22

I was too asleep to think straight, so I made the machine do my thinking for me!