diff options
-rw-r--r-- | 2024/7.hs | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/2024/7.hs b/2024/7.hs new file mode 100644 index 0000000..adcec6b --- /dev/null +++ b/2024/7.hs @@ -0,0 +1,22 @@ +{-# OPTIONS -Wno-incomplete-uni-patterns #-} +import Control.Monad (guard) + +main :: IO () +main = do + let parse line = let (lhs, _ : rhs) = break (== ':') line + in (read @Int lhs, map (read @Int) (words rhs)) + input <- map parse . lines <$> getContents + + let numdigs = go 1 + where go !d n | n < 10 = d :: Int + | otherwise = go (d+1) (n `quot` 10) + let a .|| b = a * 10 ^ numdigs b + b + + let evals _ _ acc [] = [acc] + evals p2 lhs acc (n:nums) = do + acc' <- [acc + n, acc * n] ++ (if p2 then [acc .|| n] else []) + guard (acc' <= lhs) + evals p2 lhs acc' nums + + print $ sum [lhs | (lhs, nums) <- input, lhs `elem` evals False lhs 0 nums] + print $ sum [lhs | (lhs, nums) <- input, lhs `elem` evals True lhs 0 nums] |