48 lines
1.3 KiB
Haskell
48 lines
1.3 KiB
Haskell
module Day4.Main where
|
|
|
|
import System.IO
|
|
import Data.List.Split
|
|
|
|
main :: IO ()
|
|
main = do
|
|
putStrLn "Day 4"
|
|
|
|
handle <- openFile "app/Day4/input" ReadMode
|
|
contents <- hGetContents handle
|
|
|
|
let r1 = part1 contents
|
|
putStrLn $ "part 1: " ++ show r1
|
|
|
|
let r2 = part2 contents
|
|
putStrLn $ "part 2: " ++ show r2
|
|
|
|
listToPair :: [a] -> (a, a)
|
|
listToPair l = (l !! 0, l !! 1)
|
|
|
|
type Start = Int
|
|
type End = Int
|
|
type Section = (Start, End)
|
|
|
|
parseData :: String -> [(Section, Section)]
|
|
parseData contents = transformOuter
|
|
where
|
|
pairs = map (splitOn ",") (lines contents)
|
|
ranges = (map . map) (splitOn "-") pairs
|
|
toNumbers = (map . map . map) (read :: String -> Int) ranges
|
|
transformInner = (map . map) listToPair toNumbers
|
|
transformOuter = map listToPair transformInner
|
|
|
|
|
|
contained :: Section -> Section -> Bool
|
|
contained (as, ae) (bs, be) = as <= bs && ae >= be || bs <= as && be >= ae
|
|
|
|
overlap :: Section -> Section -> Bool
|
|
overlap (as, ae) (bs, be) = bs <= as && be >= as ||
|
|
bs <= ae && be >= ae ||
|
|
as <= bs && ae >= bs ||
|
|
as <= be && ae >= be
|
|
|
|
part1, part2 :: String -> Int
|
|
part1 contents = length $ filter (uncurry contained) $ parseData contents
|
|
part2 contents = length $ filter (uncurry overlap) $ parseData contents
|