From b2b1345436fe1ef815402fc91c563754e96a47c7 Mon Sep 17 00:00:00 2001 From: eriedaberrie Date: Tue, 3 Dec 2024 22:10:00 -0800 Subject: [PATCH] 2024 day 4 --- 2024/4/Main1.hs | 23 +++++++++++++++++++++++ 2024/4/Main2.hs | 36 ++++++++++++++++++++++++++++++++++++ flake.nix | 1 + 3 files changed, 60 insertions(+) create mode 100644 2024/4/Main1.hs create mode 100644 2024/4/Main2.hs diff --git a/2024/4/Main1.hs b/2024/4/Main1.hs new file mode 100644 index 0000000..229b807 --- /dev/null +++ b/2024/4/Main1.hs @@ -0,0 +1,23 @@ +import Data.List (isPrefixOf, transpose) +import Data.Universe.Helpers (diagonals) + +countTimes :: String -> String -> Int +countTimes _ [] = 0 +countTimes s fullLine@(_:nextLine) + | s `isPrefixOf` fullLine = 1 + countTimes s (drop (length s) fullLine) + | otherwise = countTimes s nextLine + +countHoriz :: String -> Int +countHoriz l = countTimes "XMAS" l + countTimes "SAMX" l + +countLines :: [String] -> Int +countLines = sum . map countHoriz + +countAll :: [String] -> Int +countAll ls = countLines ls + + countLines (transpose ls) + + countLines (diagonals ls) + + countLines (diagonals (reverse ls)) + +main :: IO () +main = print . countAll . lines =<< readFile "data.txt" diff --git a/2024/4/Main2.hs b/2024/4/Main2.hs new file mode 100644 index 0000000..da16c22 --- /dev/null +++ b/2024/4/Main2.hs @@ -0,0 +1,36 @@ +import qualified Data.Vector as V + +isMas :: (Char, Char) -> Bool +isMas x = x == ('M', 'S') || x == ('S', 'M') + +noEnds :: V.Vector a -> Int -> Int -> Int +noEnds v i + | i == 0 || i == V.length v - 1 = const 0 + | otherwise = id + +countAll :: V.Vector (V.Vector Char) -> Int +countAll v = V.ifoldl' + (\acc x l -> acc + + noEnds + v + x + (V.ifoldl' + (\acc2 y c -> acc2 + + noEnds + l + y + (if getAt x y == 'A' + && isMas (getAt (x - 1) (y - 1), getAt (x + 1) (y + 1)) + && isMas (getAt (x + 1) (y - 1), getAt (x - 1) (y + 1)) + then 1 + else 0)) + 0 + l)) + 0 + v + where + getAt x y = v V.! x V.! y + +main :: IO () +main = print . countAll . V.fromList . map V.fromList . lines + =<< readFile "data.txt" diff --git a/flake.nix b/flake.nix index 4c2e22a..8d8d5a9 100644 --- a/flake.nix +++ b/flake.nix @@ -39,6 +39,7 @@ text text-icu unordered-containers + universe-base vector ])) ];