aboutsummaryrefslogtreecommitdiff
path: root/2024/07
diff options
context:
space:
mode:
authorMarvin Borner2024-12-07 12:20:31 +0100
committerMarvin Borner2024-12-07 12:20:31 +0100
commit299e8190b151d85423cb461f4bc31d1c881fad84 (patch)
tree1640f2880eb4ee4462f8b1dd0177d81e0150f90e /2024/07
parentb688bcf91df43653c6d39f0e58a7667f46c58165 (diff)
lazy
Diffstat (limited to '2024/07')
-rw-r--r--2024/07/solve.hs49
1 files changed, 49 insertions, 0 deletions
diff --git a/2024/07/solve.hs b/2024/07/solve.hs
new file mode 100644
index 0000000..f05013b
--- /dev/null
+++ b/2024/07/solve.hs
@@ -0,0 +1,49 @@
+import Data.Void
+import Prelude hiding ( (||) )
+import Text.Megaparsec
+import Text.Megaparsec.Char
+import qualified Text.Megaparsec.Char.Lexer as L
+
+type Parser = Parsec Void String
+
+data Equation = Equation Int [Int]
+
+equation :: Parser Equation
+equation = do
+ test <- L.decimal
+ string ": "
+ nums <- L.decimal `sepBy` char ' '
+ pure $ Equation test nums
+
+input :: Parser [Equation]
+input = equation `sepEndBy` char '\n'
+
+-- good enough
+(||) :: Int -> Int -> Int
+(||) b a = read $ show a ++ show b
+
+prune :: Int -> [Int] -> [Int]
+prune t = filter (<= t)
+
+combos :: Int -> [Int] -> [Int]
+combos t (n : ns) =
+ foldl (\s v -> prune t $ ((v +) <$> s) ++ ((v *) <$> s)) [n] ns
+
+combos2 :: Int -> [Int] -> [Int]
+combos2 t (n : ns) = foldl
+ (\s v -> prune t $ ((v +) <$> s) ++ ((v *) <$> s) ++ ((v ||) <$> s))
+ [n]
+ ns
+
+solve :: (Int -> [Int] -> [Int]) -> [Equation] -> Int
+solve f es = sum [ test | (Equation test _, m) <- zip es matches, m ]
+ where matches = (\(Equation test nums) -> test `elem` f test nums) <$> es
+
+main :: IO ()
+main = do
+ f <- readFile "input"
+ case runParser (input <* eof) "" f of
+ Right p -> do
+ print $ solve combos p
+ print $ solve combos2 p
+ Left err -> print $ errorBundlePretty err