From 6f4398b6d04adbf4997ce59693575979a26fe858 Mon Sep 17 00:00:00 2001 From: Daniele Fucini Date: Wed, 4 Dec 2024 21:29:44 +0100 Subject: [PATCH] Day 4, Part 1 --- Day4/puzzle1.hs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Day4/puzzle1.hs diff --git a/Day4/puzzle1.hs b/Day4/puzzle1.hs new file mode 100644 index 0000000..3f6692e --- /dev/null +++ b/Day4/puzzle1.hs @@ -0,0 +1,21 @@ +import Data.List (transpose, isPrefixOf) + +diagonals :: [String] -> [String] +diagonals xs = diagonals' xs ++ diagonals' ((transpose . reverse) xs) + where diagonals' xs = transpose (zipWith drop [0..] xs) + ++ transpose (zipWith drop [1..] (transpose xs)) + +countSubstrings :: String -> [String] -> Int +countSubstrings word text = sum (map (countSubstrings' word) text) + sum (map (countSubstrings' word . reverse) text) + + sum (map (countSubstrings' word) cols) + sum (map (countSubstrings' word . reverse) cols) + + sum (map (countSubstrings' word) diags) + sum (map (countSubstrings' word . reverse) diags) + where cols = transpose text + diags = diagonals text + countSubstrings' _ [] = 0 + countSubstrings' word text@(_:rest) = if word `isPrefixOf` text + then 1 + countSubstrings' word rest + else countSubstrings' word rest + +main = do + contents <- lines <$> readFile "day4.txt" + print $ countSubstrings "XMAS" contents