31 lines
853 B
Haskell
31 lines
853 B
Haskell
{-# LANGUAGE LambdaCase #-}
|
|
module Main where
|
|
|
|
import Data.Functor
|
|
|
|
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]
|
|
|
|
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]
|
|
|
|
solve2 :: [D] -> Int
|
|
solve2 = sum . (target <$>) . filter (\(D t p) -> canBeTarget' t p)
|
|
|
|
main :: IO ()
|
|
main = readFile "inputs/7" <&> parse >>= \i ->
|
|
print (solve1 i)
|
|
>> print (solve2 i)
|