advent-of-code/2020/25-Combo_Breaker/first.hs

59 lines
1.6 KiB
Haskell
Raw Permalink Normal View History

2023-05-21 22:43:08 +02:00
{-# LANGUAGE DataKinds #-}
-- requires cabal install --lib megaparsec parser-combinators mod
2023-05-21 18:00:38 +02:00
module Main (main) where
import Control.Monad (void, when)
import Data.List qualified as L
import Data.Map qualified as M
import Data.Maybe (fromJust)
2023-05-21 22:43:08 +02:00
import Data.Mod
2023-05-21 18:00:38 +02:00
import Data.Set qualified as S
import Data.Void (Void)
import Text.Megaparsec
import Text.Megaparsec.Char
import System.Exit (die)
exampleExpectedOutput = 14897079
2023-05-21 22:43:08 +02:00
type I = Mod 20201227
type Input = (I, I)
2023-05-21 18:00:38 +02:00
type Parser = Parsec Void String
2023-05-21 22:43:08 +02:00
parseInt :: Parser (I)
parseInt = do
2023-05-21 18:00:38 +02:00
n <- some digitChar
void $ optional (char '\n')
return $ read n
parseInput' :: Parser Input
parseInput' = do
2023-05-21 22:43:08 +02:00
a <- parseInt
b <- parseInt
2023-05-21 18:00:38 +02:00
void eof
return (a, b)
parseInput :: String -> IO Input
parseInput filename = do
input <- readFile filename
case runParser parseInput' filename input of
Left bundle -> die $ errorBundlePretty bundle
Right input' -> return input'
2023-05-21 22:43:08 +02:00
transform :: I -> Int -> I
transform subjectNum loopSize = subjectNum ^% loopSize
2023-05-21 18:00:38 +02:00
2023-05-21 22:43:08 +02:00
compute :: Input -> I
2023-05-21 18:00:38 +02:00
compute (cardPubKey, doorPubKey) = encryptionKey
where
cardLoopSize = fromJust . L.elemIndex cardPubKey $ map (transform 7) [0..]
doorLoopSize = fromJust . L.elemIndex doorPubKey $ map (transform 7) [0..]
encryptionKey = transform doorPubKey cardLoopSize
main :: IO ()
main = do
example <- parseInput "example"
let exampleOutput = compute example
when (exampleOutput /= exampleExpectedOutput) (die $ "example failed: got " ++ show exampleOutput ++ " instead of " ++ show exampleExpectedOutput)
input <- parseInput "input"
print $ compute input