aboutsummaryrefslogtreecommitdiff
path: root/2020/02-Password_Philosophy/second.hs
blob: 35ec5557a6fb7e62d01a056314721189024c907d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
-- requires cabal install --lib megaparsec
module Main (main) where

import Control.Monad (void, when)
import Data.Void
import Text.Megaparsec
import Text.Megaparsec.Char
import System.Exit (die)

exampleExpectedOutput = 1

data Rule = Rule { lower  :: Int
                 , higher :: Int
                 , elt    :: Char
                 , pass   :: String
                 } deriving (Show)

type Parser = Parsec Void String

parseRule :: Parser Rule
parseRule = do
  l <- try (some digitChar)
  void (char '-')
  h <- try (some digitChar)
  void (char ' ')
  e <- anySingle
  void (string ": ")
  pass <- (some letterChar)
  void (char '\n')
  return Rule { lower = (read l) - 1, higher = (read h) - 1, elt = e, pass = pass }

parseRules :: Parser [Rule]
parseRules = some parseRule <* eof

parseInput :: String -> IO [Rule]
parseInput filename = do
  input <- readFile filename
  case runParser parseRules filename input of
    Left bundle -> die $ errorBundlePretty bundle
    Right rules -> return rules

validateRule :: Rule -> Int
validateRule Rule{lower=l, higher=h, elt=e, pass=pass} = if (a /= b) then 1 else 0
  where
    a = e == pass !! l
    b = e == pass !! h

compute :: [Rule] -> Int
compute = sum . map validateRule

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