parent
3a23b8494e
commit
0e1241cf91
@ -1,28 +1,57 @@
|
||||
module Main where
|
||||
|
||||
import Data.List hiding (permutations)
|
||||
import Data.Set (Set)
|
||||
import qualified Data.Set as Set
|
||||
import qualified Data.Text.IO as TIO
|
||||
import Control.Applicative
|
||||
import qualified Data.Text as T
|
||||
import Data.Text.Read
|
||||
import qualified Data.Text.IO as TIO
|
||||
import qualified Data.Text.Read as TR
|
||||
import Data.Attoparsec.Text
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
inputs <- TIO.readFile "input.txt"
|
||||
let inputs' = T.lines inputs
|
||||
let xs = map text2decimal inputs'
|
||||
let Just entries = maybeResult $ parse entriesParser inputs
|
||||
TIO.putStrLn $ T.pack $ show $ sum $ entries2ints entries
|
||||
|
||||
data Entry = Entry
|
||||
{ policy :: Policy
|
||||
, password :: String
|
||||
} deriving (Show,Read)
|
||||
|
||||
data Policy = Policy
|
||||
{ lowest :: Int
|
||||
, highest :: Int
|
||||
, character :: Char
|
||||
} deriving (Show, Read)
|
||||
|
||||
policyParser :: Parser Policy
|
||||
policyParser = do
|
||||
low <- many digit
|
||||
string "-"
|
||||
high <- many digit
|
||||
space
|
||||
character <- letter
|
||||
let Right (lowest, _) = TR.decimal $ T.pack low
|
||||
let Right (highest, _) = TR.decimal $ T.pack high
|
||||
return Policy { lowest = lowest, highest = highest, character = character }
|
||||
|
||||
let answer = calculateAnswer xs
|
||||
entryParser :: Parser Entry
|
||||
entryParser = do
|
||||
policy <- policyParser
|
||||
char ':'
|
||||
space
|
||||
password <- many letter
|
||||
endOfLine
|
||||
return Entry { policy = policy, password = password }
|
||||
|
||||
putStrLn $ show (answer :: Int)
|
||||
checkEntry :: Entry -> Bool
|
||||
checkEntry e = let p = policy e
|
||||
n = length $ filter ((character p) ==) (password e)
|
||||
in n >= (lowest p) && n <= (highest p)
|
||||
|
||||
text2decimal :: T.Text -> Int
|
||||
text2decimal t = case decimal t of
|
||||
Right(x, _) -> x
|
||||
Left(e) -> 0
|
||||
entriesParser :: Parser [Entry]
|
||||
entriesParser = do
|
||||
entries <- many entryParser
|
||||
return entries
|
||||
|
||||
calculateAnswer :: [Int] -> Int
|
||||
calculateAnswer xs = answer $ head [ (x,y,z) | x <- xs, y <- xs, z <- xs, x+y+z==2020 ]
|
||||
where
|
||||
answer (a,b,c) = a * b * c
|
||||
entries2ints :: [Entry] -> [Int]
|
||||
entries2ints es = map (\e -> if checkEntry e then 1 else 0) es
|
||||
|
Loading…
Reference in New Issue