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:
45
day4.hs
45
day4.hs
@@ -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)
|
||||
|
Reference in New Issue
Block a user