Advent of Code 2021
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.2 KiB

{-# LANGUAGE OverloadedStrings #-}
module Day2_1 where
import System.IO (openFile, IOMode (ReadMode), hClose, hGetContents)
import Data.Text (splitOn, Text, unpack, pack)
import Data.List (mapAccumL)
data Submarine = Submarine {
horizontal :: Int
, depth :: Int
, aim :: Int
}
type Movement = (String, Int)
-- "forward 5" -> ("forward", 5)
parseInstruction :: String -> Movement
parseInstruction instr = (kind, magnitude)
where
split = map unpack $ splitOn " " $ pack instr
kind = head split
magnitude = read $ split !! 1
move :: Submarine -> Movement -> Submarine
move sub ("forward", magnitude) = sub { depth = depth sub + (aim sub * magnitude), horizontal = horizontal sub + magnitude }
move sub ("down", magnitude) = sub { aim = aim sub + magnitude }
move sub ("up", magnitude) = sub { aim = aim sub - magnitude }
main :: IO ()
main = do
input <- openFile "inputs/2.txt" ReadMode
contents <- hGetContents input
let submarine = Submarine { horizontal = 0, depth = 0, aim = 0 }
let instructions = parseInstruction <$> lines contents
let sub = foldl move submarine instructions
print $ horizontal sub * depth sub
hClose input