Day 6
This commit is contained in:
parent
b15aa5e959
commit
8bd28180de
1 changed files with 54 additions and 0 deletions
54
src/Day2506.hs
Normal file
54
src/Day2506.hs
Normal 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 (drop 1 $ 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 . 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue