day4,5: update - use parser combinators

not the cleanest, im still learning parsing in hs

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2022-12-05 23:39:03 +05:30
parent eb9ae79611
commit 38201248c4
3 changed files with 47 additions and 52 deletions

45
day4.hs
View File

@@ -1,29 +1,34 @@
import Lib (split)
import Data.Char (isDigit)
import Text.ParserCombinators.ReadP
( ReadP,
char,
many1,
readP_to_S,
satisfy,
)
main :: IO ()
main = do
input <- readFile "day4.in"
input <- map (fst . last . readP_to_S parse) . lines <$> readFile "day4.in"
putStr "Q1: "
print $ q1 input
putStr "Q2: "
print $ q2 input
q1 :: String -> Int
q1 =
length
. filter
( \x ->
let [[a, b], [c, d]] = map (map (read :: String -> Int) . split '-') $ split ',' x
in a >= c && b <= d || c >= a && d <= b
)
. lines
parse :: ReadP ((Int, Int), (Int, Int))
parse = do
a <- readInt
char '-'
b <- readInt
char ','
c <- readInt
char '-'
d <- readInt
return ((a, b), (c, d))
where
readInt :: ReadP Int
readInt = read <$> many1 (satisfy isDigit)
q2 :: String -> Int
q2 =
length
. filter
( \x ->
let [[a, b], [c, d]] = map (map (read :: String -> Int) . split '-') $ split ',' x
in b >= c && a <= d || d >= a && c <= b
)
. lines
q1, q2 :: [((Int, Int), (Int, Int))] -> Int
q1 = length . filter (\((a, b), (c, d)) -> a >= c && b <= d || c >= a && d <= b)
q2 = length . filter (\((a, b), (c, d)) -> b >= c && a <= d)