More general
This commit is contained in:
parent
fc5a496fc4
commit
c735adea4f
18
app/7.hs
18
app/7.hs
@ -1,4 +1,3 @@
|
|||||||
{-# LANGUAGE LambdaCase #-}
|
|
||||||
module Main where
|
module Main where
|
||||||
|
|
||||||
import Data.Functor
|
import Data.Functor
|
||||||
@ -8,21 +7,16 @@ data D = D { target :: Int, parts :: [Int]}
|
|||||||
parse :: String -> [D]
|
parse :: String -> [D]
|
||||||
parse = ((\(a:as) -> D (read $ takeWhile (/= ':') a) (read <$> as)) . words <$>) . lines
|
parse = ((\(a:as) -> D (read $ takeWhile (/= ':') a) (read <$> as)) . words <$>) . lines
|
||||||
|
|
||||||
canBeTarget :: Int -> [Int] -> Bool
|
canBeTarget :: Int -> [Int -> Int -> Int] -> [Int] -> Bool
|
||||||
canBeTarget _ [] = False
|
canBeTarget _ _ [] = False
|
||||||
canBeTarget t [x] = t == x
|
canBeTarget t _ [x] = t == x
|
||||||
canBeTarget t (x:y:xs) = any (canBeTarget t) [x+y:xs, x*y:xs]
|
canBeTarget t o (x:y:xs) = any (canBeTarget t o . (:xs)) ((uncurry <$> o) <*> pure (x,y))
|
||||||
|
|
||||||
solve1 :: [D] -> Int
|
solve1 :: [D] -> Int
|
||||||
solve1 = sum . (target <$>) . filter (\(D t p) -> canBeTarget t p)
|
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 :: [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 :: IO ()
|
||||||
main = readFile "inputs/7" <&> parse >>= \i ->
|
main = readFile "inputs/7" <&> parse >>= \i ->
|
||||||
|
Loading…
Reference in New Issue
Block a user