This commit is contained in:
KoenDR06 2025-12-06 15:01:18 +01:00
parent b15aa5e959
commit 41e9e71b66

54
src/Day2506.hs Normal file
View file

@ -0,0 +1,54 @@
module Main where
import Data.List (find, transpose)
import Data.Maybe (isNothing, isJust)
splitPred :: (a -> Bool) -> [a] -> [[a]]
splitPred _ [] = []
splitPred f str | isNothing $ find f str = [str]
| otherwise = takeWhile (not . f) str : splitPred f (tail $ dropWhile (not . f) str)
part1 :: String -> Int
part1 = sum . map calcOne . transpose . parser
where
parser :: String -> [[String]]
parser = map splitLine . lines
where
splitLine :: String -> [String]
splitLine = filter (not . null) . words
calcOne :: [String] -> Int
calcOne xs = foldl1 operation operands
where
operation = if last xs == "+" then (+) else (*)
operands :: [Int]
operands = map read $ drop 1 $ reverse xs
part2 :: String -> Int
part2 = sum . map calcOne . map transpose . parse
where
parse = splitPred (all (==' ')) . transpose . lines
calcOne :: [String] -> Int
calcOne xs = foldl1 operation operands
where
operation = getOperation xs
operands = getOperands xs
getOperands :: [String] -> [Int]
getOperands xs = map (read) $ transpose $ operands
where
operands = take (length xs - 1) xs
getOperation :: [String] -> (Int -> Int -> Int)
getOperation xs = if isJust $ find (=='+') $ last xs then (+) else (*)
main :: IO ()
main = do
str <- getContents
print $ part1 str
print $ part2 str