day2: update - use implement ordering like normal people
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
62
day2.hs
62
day2.hs
@@ -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
|
||||
|
12
flake.nix
12
flake.nix
@@ -13,18 +13,18 @@
|
||||
pkgs = import nixpkgs {
|
||||
inherit system;
|
||||
};
|
||||
src = ./.;
|
||||
in
|
||||
{
|
||||
devShells = with pkgs; rec {
|
||||
default = mkShell {
|
||||
buildInputs = [ ghc ];
|
||||
};
|
||||
withLsp = mkShell {
|
||||
with pkgs; {
|
||||
devShells.default = mkShell {
|
||||
buildInputs = [
|
||||
ghc
|
||||
haskell-language-server
|
||||
];
|
||||
};
|
||||
apps.default = {
|
||||
type = "app";
|
||||
program = "${ghc}/bin/runhaskell";
|
||||
};
|
||||
}
|
||||
);
|
||||
|
Reference in New Issue
Block a user