feat(day5): part 1 babyyyy
This commit is contained in:
parent
0b073c049c
commit
14a6f5ce1d
44
day5/Main.hs
Normal file
44
day5/Main.hs
Normal file
|
@ -0,0 +1,44 @@
|
|||
module Main where
|
||||
|
||||
import System.Environment (getArgs)
|
||||
import Data.Maybe (mapMaybe)
|
||||
|
||||
import Text.Parsec (parse, Parsec, endBy, sepBy1, char, newline, many)
|
||||
import Text.ParserCombinators.Parsec.Number (decimal)
|
||||
|
||||
type PageOrdering = (Int, Int)
|
||||
type PagesUpdate = [Int]
|
||||
|
||||
printInfo :: Parsec String () ([PageOrdering], [PagesUpdate])
|
||||
printInfo = (,) <$> orderings <*> (newline *> pagesUpdates) <* many (char '\n')
|
||||
where
|
||||
pagesUpdates :: Parsec String () [PagesUpdate]
|
||||
pagesUpdates = endBy (sepBy1 decimal $ char ',') newline
|
||||
|
||||
orderings :: Parsec String () [PageOrdering]
|
||||
orderings = endBy ((,) <$> decimal <*> (char '|' *> decimal)) $ char '\n'
|
||||
|
||||
allDependencies :: [a] -> [(a, a)]
|
||||
allDependencies (h:tl) = map (flip (,) h) tl ++ allDependencies tl
|
||||
allDependencies [] = []
|
||||
|
||||
middleElement :: [a] -> Maybe a
|
||||
middleElement [] = Nothing
|
||||
middleElement [a] = Just a
|
||||
middleElement (_:h':tl) = case reverse (h':tl) of
|
||||
(_:middle) -> middleElement middle
|
||||
[] -> Nothing
|
||||
|
||||
part1 :: FilePath -> IO Int
|
||||
part1 fp = do
|
||||
content <- readFile fp
|
||||
(requiredOrderings, pagesUpdates) <- either (fail . show) return $ parse printInfo fp content
|
||||
let wellOrdered = filter (all (`notElem` requiredOrderings) . allDependencies) pagesUpdates
|
||||
return $ sum $ mapMaybe middleElement wellOrdered
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
args <- getArgs
|
||||
(fp:_) <- return args
|
||||
resPart1 <- part1 fp
|
||||
putStrLn $ "Solution (Part 1) : " ++ show resPart1
|
1362
day5/puzzle_input
Normal file
1362
day5/puzzle_input
Normal file
File diff suppressed because it is too large
Load diff
28
day5/test_input
Normal file
28
day5/test_input
Normal file
|
@ -0,0 +1,28 @@
|
|||
47|53
|
||||
97|13
|
||||
97|61
|
||||
97|47
|
||||
75|29
|
||||
61|13
|
||||
75|53
|
||||
29|13
|
||||
97|29
|
||||
53|29
|
||||
61|53
|
||||
97|53
|
||||
61|29
|
||||
47|13
|
||||
75|47
|
||||
97|75
|
||||
47|61
|
||||
75|61
|
||||
47|29
|
||||
75|13
|
||||
53|13
|
||||
|
||||
75,47,61,53,29
|
||||
97,61,53,29,13
|
||||
75,29,13
|
||||
75,97,47,61,53
|
||||
61,13,29
|
||||
97,13,75,29,47
|
|
@ -50,3 +50,13 @@ executable day4
|
|||
parsec ^>= 3.1.17.0
|
||||
hs-source-dirs: day4
|
||||
default-language: Haskell2010
|
||||
|
||||
executable day5
|
||||
import: warnings
|
||||
main-is: Main.hs
|
||||
build-depends:
|
||||
base ^>=4.18.2.1,
|
||||
parsec ^>= 3.1.17.0,
|
||||
parsec-numbers ^>= 0.1.0
|
||||
hs-source-dirs: day5
|
||||
default-language: Haskell2010
|
||||
|
|
Loading…
Reference in a new issue