aoc2021/2.hs
2021-12-02 13:47:03 +01:00

31 lines
1.0 KiB
Haskell

{-# LANGUAGE ScopedTypeVariables #-}
main = do
lines <- readFile "2.in"
putStrLn . show . solve . parseInput . words $ lines
where
solve = partB
parseInput :: [ String ] -> [ (String, Integer) ]
parseInput [] = []
parseInput [x] = []
parseInput (x:y:r) = (x, read y) : parseInput r
-- solves all lines, returns a string
partA :: [(String, Integer)] -> Integer
partA = (uncurry (*)) . foldl parseCommand (0,0)
where
-- (horizontal, vertical)
parseCommand (a, b) ("forward", x) = (a + x, b)
parseCommand (a, b) ("down", x) = (a, b + x)
parseCommand (a, b) ("up", x) = (a, b - x)
parseCommand _ _ = (0, 0)
partB :: [(String, Integer)] -> Integer
partB = (\(x,y,_) -> x * y) . foldl parseCommand (0, 0, 0)
where
-- (horiz, vert, aim)
parseCommand (a, b, c) ("forward", x) = (a + x, b + c * x, c)
parseCommand (a, b, c) ("down", x) = (a, b, c + x)
parseCommand (a, b, c) ("up", x) = (a, b, c - x)
parseCommand _ _ = (0, 0, 0)