42 lines
1.0 KiB
Haskell
42 lines
1.0 KiB
Haskell
import Control.Exception (assert)
|
|
|
|
main :: IO ()
|
|
main = do
|
|
instructions <- getContents
|
|
putStrLn (solution1 instructions)
|
|
|
|
solution1 :: String -> String
|
|
solution1 input = show (uncurry (*) (navigate (parseInstructions input)))
|
|
|
|
parseInstructions :: String -> [(Int, Int)]
|
|
parseInstructions instructions =
|
|
map parseLine (lines instructions)
|
|
where
|
|
parseLine line = case break (== ' ') line of
|
|
("forward", distance) -> (read distance, 0)
|
|
("down", distance) -> (0, read distance)
|
|
("up", distance) -> (0, (-read distance))
|
|
_ -> error "Invalid line"
|
|
|
|
navigate :: [(Int, Int)] -> (Int, Int)
|
|
navigate instructions =
|
|
foldl1 sumTuples instructions
|
|
where
|
|
sumTuples :: (Int, Int) -> (Int, Int) -> (Int, Int)
|
|
sumTuples (a, b) (c, d) = (a + c, b + d)
|
|
|
|
-- Tests
|
|
|
|
testInput1 :: String
|
|
testInput1 = unlines [
|
|
"forward 5",
|
|
"down 5",
|
|
"forward 8",
|
|
"up 3",
|
|
"down 8",
|
|
"forward 2"
|
|
]
|
|
|
|
test1 :: String
|
|
test1 = assert ((solution1 testInput1) == "150") "success"
|