Both stars of Day 4!

This commit is contained in:
Steph 2022-12-04 14:03:52 +01:00
parent 9d1c6f30c5
commit a2f722c670
4 changed files with 1050 additions and 1 deletions

View File

@ -32,4 +32,4 @@ executable aoc2022
build-depends: base ^>=4.16.3.0, split ^>=0.2.3.5
hs-source-dirs: app
default-language: Haskell2010
other-modules: Day1.Main Day2.Main Day3.Main
other-modules: Day1.Main Day2.Main Day3.Main Day4.Main

47
2022/app/Day4/Main.hs Normal file
View File

@ -0,0 +1,47 @@
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

1000
2022/app/Day4/input Normal file

File diff suppressed because it is too large Load Diff

View File

@ -3,9 +3,11 @@ module Main where
import qualified Day1.Main as Day1
import qualified Day2.Main as Day2
import qualified Day3.Main as Day3
import qualified Day4.Main as Day4
main :: IO ()
main = do
Day1.main
Day2.main
Day3.main
Day4.main