Browse Source

Solved day 1 part 1

main 2020-02-A
Sam Hatfield 5 months ago
parent
commit
0e1241cf91
Signed by: sehqlr GPG Key ID: 6B1E0EDE1530CA2B
  1. 63
      Main.hs
  2. 5
      advent-of-code.cabal
  3. 1201
      input.txt
  4. 5
      package.yaml

63
Main.hs

@ -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

5
advent-of-code.cabal

@ -20,8 +20,9 @@ executable advent-of-code
main-is: Main.hs
other-modules:
Paths_advent_of_code
default-extensions: OverloadedStrings
build-depends:
base
, containers
attoparsec
, base
, text
default-language: Haskell2010

1201
input.txt
File diff suppressed because it is too large
View File

5
package.yaml

@ -7,10 +7,13 @@ license: MIT
build-type: Simple
git: "https://git.bytes.zone/sehqlr/advent-of-code"
default-extensions:
- OverloadedStrings
dependencies:
- base
- containers
- text
- attoparsec
executable:
main: Main.hs
Loading…
Cancel
Save