From 69bf5ffbf16251e82403af026ec4b61c0243eb81 Mon Sep 17 00:00:00 2001 From: pingu Date: Sat, 7 Dec 2024 12:03:45 +0100 Subject: [PATCH] More general --- app/7.hs | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/app/7.hs b/app/7.hs index cbcf743..4eba000 100644 --- a/app/7.hs +++ b/app/7.hs @@ -8,21 +8,16 @@ data D = D { target :: Int, parts :: [Int]} parse :: String -> [D] parse = ((\(a:as) -> D (read $ takeWhile (/= ':') a) (read <$> as)) . words <$>) . lines -canBeTarget :: Int -> [Int] -> Bool -canBeTarget _ [] = False -canBeTarget t [x] = t == x -canBeTarget t (x:y:xs) = any (canBeTarget t) [x+y:xs, x*y:xs] +canBeTarget :: Int -> [Int -> Int -> Int] -> [Int] -> Bool +canBeTarget _ _ [] = False +canBeTarget t _ [x] = t == x +canBeTarget t ops (x:y:xs) = any (canBeTarget t ops . (:xs)) ((uncurry <$> ops) <*> pure (x,y)) solve1 :: [D] -> Int -solve1 = sum . (target <$>) . filter (\(D t p) -> canBeTarget t p) - -canBeTarget' :: Int -> [Int] -> Bool -canBeTarget' _ [] = False -canBeTarget' t [x] = t == x -canBeTarget' t (x:y:xs) = any (canBeTarget' t) [x+y:xs, x*y:xs, read (show x ++ show y):xs] +solve1 = sum . (target <$>) . filter (\(D t p) -> canBeTarget t [(*), (+)] p) solve2 :: [D] -> Int -solve2 = sum . (target <$>) . filter (\(D t p) -> canBeTarget' t p) +solve2 = sum . (target <$>) . filter (\(D t p) -> canBeTarget t [(*), (+), \a b -> read (show a ++ show b)] p) main :: IO () main = readFile "inputs/7" <&> parse >>= \i ->