2021-12-02 19:24:58 +00:00
|
|
|
{-# LANGUAGE OverloadedStrings #-}
|
|
|
|
|
|
|
|
module Day2 where
|
|
|
|
|
|
|
|
import System.IO (openFile, IOMode (ReadMode), hClose, hGetContents)
|
|
|
|
import Data.Text (splitOn, Text, unpack, pack)
|
|
|
|
|
|
|
|
|
|
|
|
data Submarine = Submarine {
|
|
|
|
horizontal :: Int
|
|
|
|
, depth :: Int
|
2021-12-02 19:35:45 +00:00
|
|
|
}
|
2021-12-02 19:24:58 +00:00
|
|
|
|
|
|
|
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 { horizontal = horizontal sub + magnitude }
|
|
|
|
move sub ("down", magnitude) = sub { depth = depth sub + magnitude }
|
|
|
|
move sub ("up", magnitude) = sub { depth = depth sub - magnitude }
|
|
|
|
|
|
|
|
(++) :: Submarine -> Submarine -> Submarine
|
|
|
|
x ++ y = Submarine { horizontal = horizontal x + horizontal y, depth = depth x + depth y }
|
|
|
|
|
|
|
|
main :: IO ()
|
|
|
|
main = do
|
|
|
|
input <- openFile "inputs/2.txt" ReadMode
|
|
|
|
contents <- hGetContents input
|
|
|
|
|
|
|
|
let submarine = Submarine { horizontal = 0, depth = 0 }
|
|
|
|
let instructions = parseInstruction <$> lines contents
|
|
|
|
let sub = foldl move submarine instructions
|
|
|
|
|
|
|
|
print $ horizontal sub * depth sub
|
|
|
|
|
2021-12-02 19:35:45 +00:00
|
|
|
hClose input
|