From 0b073c049c7059b0f89387fa18e72640fa0c5a0b Mon Sep 17 00:00:00 2001 From: kalmenn Date: Mon, 9 Dec 2024 01:42:39 +0100 Subject: [PATCH] feat(day4): Implement part2 --- day4/Main.hs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/day4/Main.hs b/day4/Main.hs index 3e0bf6c..52d8cba 100644 --- a/day4/Main.hs +++ b/day4/Main.hs @@ -44,9 +44,38 @@ part1 fp = do Left e -> fail $ "Oh no! " ++ show e Right v -> return v +windows3 :: [a] -> [(a, a, a)] +windows3 (a:b:c:tl) = (a, b, c) : windows3 (b:c:tl) +windows3 _ = [] + +windows3x3 :: [[a]] -> [((a, a, a), (a, a, a), (a, a, a))] +windows3x3 ls = [(wa, wb, wc) + | (a, b, c) <- windows3 ls + , (wa, wb, wc) <- zip3 (windows3 a) (windows3 b) (windows3 c)] + +countCrossMAS :: [String] -> Int +countCrossMAS = sum + . map (\((tl, _, tr), + (_ , c, _ ), + (bl, _, br)) -> + if isMAS [tl, c, br] && isMAS [tr, c, bl] then 1 else 0) + . windows3x3 + where + isMAS :: String -> Bool + isMAS = (||) <$> (==) "MAS" <*> (==) "SAM" + +part2 :: FilePath -> IO Int +part2 fp = do + content <- readFile fp + case parse rows fp content of + Left e -> fail $ "Oh no! " ++ show e + Right r -> return $ countCrossMAS r + main :: IO () main = do args <- getArgs (fp:_) <- return args resPart1 <- part1 fp + resPart2 <- part2 fp putStrLn $ "Solution (Part 1) : " ++ show resPart1 + putStrLn $ "Solution (Part 2) : " ++ show resPart2