Skip to content

Instantly share code, notes, and snippets.

@gnusosa
Created December 3, 2021 20:15
Show Gist options
  • Save gnusosa/9c4ae7d9ee8c4dc20f999c5945680ad1 to your computer and use it in GitHub Desktop.
Save gnusosa/9c4ae7d9ee8c4dc20f999c5945680ad1 to your computer and use it in GitHub Desktop.
{-# LANGUAGE FlexibleContexts #-}
import qualified Data.Text as Text
import qualified Data.Text.Read as Text
import qualified Data.Text.IO as Text
import qualified Data.Either as Either
import qualified Data.List as L
import qualified Data.Map.Strict as Map
import Data.Maybe
counter = Map.fromList [("horizontal", 0), ("depth", 0), ("aim", 0)]
getInput = Text.lines <$> Text.readFile "day2.txt"
commands = do
return . collectCommands . map (\x -> (Text.unpack (x !! 0), fst . head $ Either.rights [(Text.decimal $ x !! 1)])) . map (Text.split (== ' ')) =<< getInput
updateCounter "forward" x c = increaseDepth x (Map.adjust (x +) "horizontal" c)
updateCounter "backward" x c = Map.adjust (\v -> v - x) "horizontal" c
updateCounter "down" x c = Map.adjust (x +) "aim" c
updateCounter "up" x c = Map.adjust (\v -> v - x) "aim" c
collectCommands xs = foldl (\acc comm -> updateCounter (fst comm) (snd comm) acc) counter xs
multiplyFinalValues c = (*) <$> (Map.lookup "depth" c) <*> (Map.lookup "horizontal" c)
increaseDepth x c = Map.adjust (aim +) "depth" c
where aim = fromJust $ (*) <$> Map.lookup "aim" c <*> Just x
main = do
comms <- commands
return $ multiplyFinalValues comms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment