day2: Complete second puzzle

This commit is contained in:
Tristan Daniël Maat 2021-12-03 21:59:05 +00:00
parent a497af5d30
commit 31305e22f8
Signed by: tlater
GPG key ID: 49670FD774E43268

View file

@ -4,10 +4,14 @@ main :: IO ()
main = do main = do
instructions <- getContents instructions <- getContents
putStrLn (solution1 instructions) putStrLn (solution1 instructions)
putStrLn (solution2 instructions)
solution1 :: String -> String solution1 :: String -> String
solution1 input = show (uncurry (*) (navigate (parseInstructions input))) solution1 input = show (uncurry (*) (navigate (parseInstructions input)))
solution2 :: String -> String
solution2 input = show (uncurry (*) (navigate2 (parseInstructions input)))
parseInstructions :: String -> [(Int, Int)] parseInstructions :: String -> [(Int, Int)]
parseInstructions instructions = parseInstructions instructions =
map parseLine (lines instructions) map parseLine (lines instructions)
@ -25,6 +29,15 @@ navigate instructions =
sumTuples :: (Int, Int) -> (Int, Int) -> (Int, Int) sumTuples :: (Int, Int) -> (Int, Int) -> (Int, Int)
sumTuples (a, b) (c, d) = (a + c, b + d) sumTuples (a, b) (c, d) = (a + c, b + d)
navigate2 :: [(Int, Int)] -> (Int, Int)
navigate2 instructions =
takePosition (foldl navigate (0, 0, 0) instructions)
where
navigate :: (Int, Int, Int) -> (Int, Int) -> (Int, Int, Int)
navigate (horz, depth, aim) (speed, dir) = (horz + speed, depth + aim * speed, aim + dir)
takePosition :: (Int, Int, Int) -> (Int, Int)
takePosition (x,y,_) = (x,y)
-- Tests -- Tests
testInput1 :: String testInput1 :: String
@ -39,3 +52,6 @@ testInput1 = unlines [
test1 :: String test1 :: String
test1 = assert ((solution1 testInput1) == "150") "success" test1 = assert ((solution1 testInput1) == "150") "success"
test2 :: String
test2 = assert ((solution2 testInput1) == "900") "success"