day12, simple recursive solution

now to memoize it…
This commit is contained in:
Gattix 2023-12-25 18:10:50 +01:00
parent 5b31f9effb
commit 1a5e8a6e62

View File

@ -1,5 +1,4 @@
import Control.Arrow
import Control.Monad
import Data.List
main :: IO ()
@ -9,32 +8,20 @@ parse :: String -> (String, [Int])
parse = second (read . ('[' :) . (++ "]") . tail) . break (== ' ')
day12 :: [(String, [Int])] -> Int
day12 = sum . map (length . genArrangements)
day12 = sum . map (uncurry (countArr 0))
part2ify :: (String, [Int]) -> (String, [Int])
part2ify (s, xs) = (intercalate "?" $ replicate 5 s, concat $ replicate 5 xs)
genMin :: [Int] -> [String]
genMin = foldr (\x -> (:) (replicate x '#' ++ ".")) []
genDots :: Int -> Int -> [[Int]]
genDots n x = filter (\xs -> sum xs == x) $ replicateM n [0 .. x]
buildMaxeds :: [String] -> [[Int]] -> [String]
buildMaxeds ss = map (build ss)
build :: [String] -> [Int] -> String
build [] [x] = replicate x '.'
build (s:ss) (x:xs) = replicate x '.' ++ s ++ build ss xs
genArrangements :: (String, [Int]) -> [String]
genArrangements (s, xs) = filter f $ buildMaxeds (genMin xs) (genDots w l)
where
f x = and (zipWith wEq s x)
w = succ $ length xs
l = length s - sum xs - pred (length xs)
wEq :: Char -> Char -> Bool
wEq _ '?' = True
wEq '?' _ = True
wEq c1 c2 = c1 == c2
countArr :: Int -> String -> [Int] -> Int
countArr 0 [] [] = 1
countArr _ [] [] = 0
countArr _ ss [] = fromEnum $ not $ any (=='#') ss
countArr streak [] [i] = fromEnum $ streak==i
countArr streak (s:ss) (i:is)
| s=='.' && streak == 0 = countArr 0 ss (i:is)
| s=='.' && streak == i = countArr 0 ss is
| s=='.' = 0
| s=='#' = countArr (succ streak) ss (i:is)
| s=='?' = countArr streak ('.':ss) (i:is) + countArr streak ('#':ss) (i:is)
countArr _ _ _ = 0