Day 7, Part 2

This commit is contained in:
daniele 2024-12-07 15:33:03 +01:00
parent 67aabf4d63
commit 0038d22c5b
Signed by: fuxino
GPG Key ID: 981A2B2A3BBF5514

27
Day7/puzzle2.hs Normal file
View File

@ -0,0 +1,27 @@
import Data.List (transpose)
import Data.List.Split (splitOn)
type Equation = (Int, [Int])
concatInt :: Int -> Int -> Int
concatInt x y = read $ show x ++ show y
isSolvable :: Int -> Equation -> Bool
isSolvable cur (result, []) = cur == result
isSolvable cur (result, [x]) = cur + x == result || cur * x == result || cur `concatInt` x == result
isSolvable cur (result, x:y:ys) = isSolvable (cur + x + y) (result, ys)
|| isSolvable ((cur + x) * y) (result, ys)
|| isSolvable ((cur + x) `concatInt` y) (result, ys)
|| isSolvable (cur * x + y) (result, ys)
|| isSolvable (cur * x * y) (result, ys)
|| isSolvable ((cur * x) `concatInt` y) (result, ys)
|| isSolvable ((cur `concatInt` x) + y) (result, ys)
|| isSolvable ((cur `concatInt` x) * y) (result, ys)
|| isSolvable ((cur `concatInt` x) `concatInt` y) (result, ys)
main = do
[x, y] <- transpose . map (splitOn ":") . lines <$> readFile "day7.txt"
let results = map read x
values = map read <$> map words y
equations = zip results values
print . sum . map fst $ filter (isSolvable 0) equations