summaryrefslogtreecommitdiff
path: root/2024/7.hs
blob: adcec6b80de2ec63a4c675a97cc23b02dfedc4fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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]