2020-25 in haskell v2

This commit is contained in:
Julien Dessaux 2023-05-21 22:43:08 +02:00
parent 1aa25c3aa1
commit 73f06861ac
Signed by: adyxax
GPG key ID: F92E51B86E07177E

View file

@ -1,32 +1,34 @@
-- requires cabal install --lib megaparsec parser-combinators {-# LANGUAGE DataKinds #-}
-- requires cabal install --lib megaparsec parser-combinators mod
module Main (main) where module Main (main) where
import Control.Monad (void, when) import Control.Monad (void, when)
import Data.List qualified as L import Data.List qualified as L
import Data.Map qualified as M import Data.Map qualified as M
import Data.Maybe (fromJust) import Data.Maybe (fromJust)
import Data.Mod
import Data.Set qualified as S import Data.Set qualified as S
import Data.Void (Void) import Data.Void (Void)
import Math.NumberTheory.Powers.Modular
import Text.Megaparsec import Text.Megaparsec
import Text.Megaparsec.Char import Text.Megaparsec.Char
import System.Exit (die) import System.Exit (die)
exampleExpectedOutput = 14897079 exampleExpectedOutput = 14897079
type Input = (Integer, Integer) type I = Mod 20201227
type Input = (I, I)
type Parser = Parsec Void String type Parser = Parsec Void String
parseInteger :: Parser Integer parseInt :: Parser (I)
parseInteger = do parseInt = do
n <- some digitChar n <- some digitChar
void $ optional (char '\n') void $ optional (char '\n')
return $ read n return $ read n
parseInput' :: Parser Input parseInput' :: Parser Input
parseInput' = do parseInput' = do
a <- parseInteger a <- parseInt
b <- parseInteger b <- parseInt
void eof void eof
return (a, b) return (a, b)
@ -37,10 +39,10 @@ parseInput filename = do
Left bundle -> die $ errorBundlePretty bundle Left bundle -> die $ errorBundlePretty bundle
Right input' -> return input' Right input' -> return input'
transform :: Integer -> Int -> Integer transform :: I -> Int -> I
transform subjectNum loopSize = powMod subjectNum loopSize 20201227 transform subjectNum loopSize = subjectNum ^% loopSize
compute :: Input -> Integer compute :: Input -> I
compute (cardPubKey, doorPubKey) = encryptionKey compute (cardPubKey, doorPubKey) = encryptionKey
where where
cardLoopSize = fromJust . L.elemIndex cardPubKey $ map (transform 7) [0..] cardLoopSize = fromJust . L.elemIndex cardPubKey $ map (transform 7) [0..]
@ -52,6 +54,5 @@ main = do
example <- parseInput "example" example <- parseInput "example"
let exampleOutput = compute example let exampleOutput = compute example
when (exampleOutput /= exampleExpectedOutput) (die $ "example failed: got " ++ show exampleOutput ++ " instead of " ++ show exampleExpectedOutput) when (exampleOutput /= exampleExpectedOutput) (die $ "example failed: got " ++ show exampleOutput ++ " instead of " ++ show exampleExpectedOutput)
print "OK"
input <- parseInput "input" input <- parseInput "input"
print $ compute input print $ compute input