day 4: alternate solution

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2024-12-04 15:15:02 +05:30
parent 1dc5135987
commit ca69182e55
3 changed files with 47 additions and 1 deletions

View File

@@ -43,3 +43,9 @@ executable day4
hs-source-dirs: src hs-source-dirs: src
main-is: Day4.hs main-is: Day4.hs
build-depends: libaoc build-depends: libaoc
executable day4alt
import: common
hs-source-dirs: src
main-is: Day4Alt.hs
build-depends: libaoc

View File

@@ -1,6 +1,6 @@
module AoC where module AoC where
import Data.List (transpose) import Data.List (tails, transpose)
import Text.Parsec (ParseError) import Text.Parsec (ParseError)
-- extract Right value after parsing -- extract Right value after parsing
@@ -27,3 +27,7 @@ findSubstrings sub str = findSubstrings' sub str 0
findSubstrings' sub str@(x : xs) idx findSubstrings' sub str@(x : xs) idx
| take (length sub) str == sub = idx : findSubstrings' sub xs (idx + 1) | take (length sub) str == sub = idx : findSubstrings' sub xs (idx + 1)
| otherwise = findSubstrings' sub xs (idx + 1) | otherwise = findSubstrings' sub xs (idx + 1)
-- get all subarrays of size n
subArrays :: Int -> [[a]] -> [[[a]]]
subArrays n xss = [[take n t | t <- tails xs] | xs <- xss]

36
src/Day4Alt.hs Normal file
View File

@@ -0,0 +1,36 @@
module Main where
import qualified AoC as A (diagonals, subArrays)
import Data.List (isPrefixOf, tails, transpose)
part1 :: [[Char]] -> Int
part1 grid =
(sum . concatMap countXmas)
[ grid,
transpose grid,
A.diagonals grid,
A.diagonals $ map reverse grid
]
where
countXmas :: [[Char]] -> [Int]
countXmas = map (length . filter ((||) <$> isPrefixOf "XMAS" <*> isPrefixOf "SAMX") . tails)
part2 :: [[Char]] -> Int
part2 grid =
let groups = concat $ A.subArrays 3 $ transpose $ A.subArrays 3 grid
in length $ filter check groups
where
check :: [[Char]] -> Bool
check
[ [a, _, b],
[_, 'A', _],
[c, _, d]
] = elem [a, d] ["MS", "SM"] && elem [b, c] ["MS", "SM"]
check _ = False
main :: IO ()
main =
do
raw <- lines <$> readFile "./inputs/day4.in"
putStr "Part 1: " >> print (part1 raw)
putStr "Part 2: " >> print (part2 raw)